From d12c0ab2e7a7d1d40f62991e3d097bd9090cc2ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:48:19 +1300 Subject: [PATCH 01/23] Keep delegation JWTs out of Redis and deny unproved presence elevation --- .../game-session-service/runtime-and-data.md | 3 +- ...m-architecture-redis-reset-and-recovery.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 + .../player-access-and-session.md | 12 +- ...r-experience-commands-and-communication.md | 12 +- .../common/security/SessionClaims.java | 35 -- .../common/security/SessionClaimsTest.java | 30 +- .../GameplayLocalPathReadinessProbe.java | 2 +- .../gamesession/service/SessionContext.java | 26 ++ .../impl/GameplayPresenceRoleClassifier.java | 41 --- .../impl/RedisGameplayPresenceService.java | 112 ++++--- ...RedisMovementEffectIdempotencyService.java | 34 +- .../impl/RedisSessionContextService.java | 30 +- ...SecretAndPresenceRedisIntegrationTest.java | 314 ++++++++++++++++++ .../impl/FakeGameplayPresenceService.java | 12 +- .../text/SessionResumptionFlowTest.java | 36 +- .../text/TextCommandInterpreterTest.java | 4 +- .../command/text/WhoCommandHandlerTest.java | 16 +- .../GameplayLocalPathReadinessProbeTest.java | 30 +- .../GameplayPresenceRoleClassifierTest.java | 178 ---------- .../RedisGameplayPresenceServiceTest.java | 156 +++++++-- ...sMovementEffectIdempotencyServiceTest.java | 36 +- .../impl/RedisSessionContextServiceTest.java | 125 ++++++- ...essionContextSerializationTestSupport.java | 38 +++ 24 files changed, 843 insertions(+), 443 deletions(-) delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ca2734d7e3..01bd9379da 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -59,9 +59,10 @@ The sections below define the target-state runtime contract. Current implementat - Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. - Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. -- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. +- Current Redis session-context and movement writers persist a projection without the raw `game-session-account-delegation` JWT, preserving other binding fields. Canonical/index and movement legacy reads return the same non-secret projection without rewriting retained values or extending their lifetime. Existing stored bytes are not globally erased: owner-fenced retained-value cleanup, complete rotation/rebind metadata and the rest of [ADR 0031](../../decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) remain incomplete. Focused receiving proof and limits are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#session-secret-and-presence-containment). - An unregistered initial-LOGIN journal, cleanup owner and exact-context Redis CAS/closure adapter are prepared independently of that legacy handler. The adapter follows the [initial-context owner](../../system-architecture-redis.md#initial-login-context-aggregate) and requires the separately supplied protected binding and external qualification; it does not implement legacy Redis context save/delete, trusted TCP custody or runtime LOGIN. Qualified source and physical proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. +- Current live-presence registration, returned legacy projections and ordinary activity updates use `PLAYER`: no independently verified gameplay-grant carrier is available. JWT global/scoped roles and retained cached elevation grant no gameplay capability. Read projection does not persist the demotion or refresh TTL; ordinary activity writes retain their existing lifetime behavior and preserve other fields. The [authentication owner](../../system-architecture-authentication.md#global-role-to-route-class-matrix-normative) defines grant authority; [Player Experience](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#communication-social-and-presence) records implementation/proof limits. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 3b64506781..13a48e6578 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -236,7 +236,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | -| `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. New context/movement writes omit the raw delegation JWT; legacy reads project without rehydrating it or authorizing retained-value cleanup, as recorded by [Game Session runtime](./microservices/game-session-service/runtime-and-data.md#implementation-status). Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | | `session:game:direct-text-worlds:v1:` | Coordination | **Reset-sensitive, not preservable UI state** | Loss, expiry or an applicable session reset invalidates the original public WORLDS menu and requires fresh `WORLDS`. A present undecodable value is refused until actual key expiry; no current supported administrative repair path is implemented, so a malformed key without a TTL can block fresh discovery indefinitely, as defined by the linked menu owner; the old snapshot is never reconstructed or its expiry extended. A tenant/region reset cannot infer key membership from this tenantless UUID key or from the numeric transport-session ID, and must not use a wildcard scan to delete, rebuild, or preserve affected menus. Cluster reset drops the family. | Game Session owns one full-key-hashed key per canonical original proxy UUID. This is observational public UI only, contains no Account identity, credentials, REALMS scope, or JOIN intent, and is outside authenticated gameplay `--preserve-sessions` recovery. See [Direct-text WORLDS UI menu](./system-architecture-redis.md#direct-text-worlds-ui-menu). | | `session:game:initial-context:v1:*` | Coordination | **Reset-sensitive, non-preservable pre-auth state** | A whole-family invalidation declares its global impact and closes the affected initial-LOGIN boundary. A tenant or region reset cannot infer membership of tenantless records or delete this family under a tenant filter. Current recovery authority must qualify the exact global family, fence and protected binding before a physical closure continuation; missing records, retained receipts and bare absence never establish that qualification. | No expiry or recreation of missing/replaced/closed original contexts. The production external qualification producer remains unavailable; controlled fixture leases do not prove reset/restore continuity. See the [initial-context owner](./system-architecture-redis.md#initial-login-context-aggregate). | | `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index a3d4a59744..8dda305151 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +Local session-state reception strips raw delegation JWTs from Redis writes and returned legacy context/movement projections, and presence remains `PLAYER` without independently verified grants. The owning [Player Access record](./player-access-and-session.md#session-secret-and-presence-containment) and [Player Experience record](./player-experience-commands-and-communication.md#communication-social-and-presence) retain detailed scope, qualified receiving proof and cleanup/authority gaps. This does not install canonical bindings, recover credentials, grant gameplay capabilities or activate runtime admission. + ### Historical StartSession receiver transport denials At donor HEAD `5f92bc4a364f07799b19e25180166f5bc81157d7`, five freshly executed cases in the [historical owner-read transport test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java) pass against the actual historical client and unregistered receiver over loopback mTLS. Exact same-namespace World and Account clients reach the mocked repository and receive `FAILED_PRECONDITION` for missing retained evidence. Wrong-service or wrong-namespace client certificates, wrong-service or wrong-namespace server certificates, a missing client certificate, and injected authenticated end-user context are rejected before owner access. Receiving HEAD `bf09b5ac77eeae6969d3f3fa1aa8d83c35c25c18` separately passed all five cases freshly at 2026-10-17 08:06:21 UTC, with zero failures, errors or skips. The affected test static analysis, formatting, documentation links and Markdown checks also passed in the canonical gate. 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 0942454c5c..3bb835ddbd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -491,7 +491,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | -| `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | +| `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership or cached-success replay. Pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. @@ -634,6 +634,12 @@ The lifecycle classes are deliberately distinct: Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. Earlier first-party screen-buffer tests exercised a post-logout replay path, but that behavior is historical: current public first-party `LOGIN`/`PLAY` is denied before admission and cannot establish current reconnect eligibility. Revisit the target rule that deliberate logout is not a recovery replay path when the protected first-party receiver is qualified. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. +### Session secret and presence containment + +The local #2857 receiving group applies the process-local delegation-token rule from [ADR 0031](../../architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) to the current Redis context family. Canonical/index and movement/effect writes serialize `SessionContext.withoutJwt()`; legacy lookup and replay projections remove the token only from returned values. Account UUID, room text, route fields and `firstPartyConnectContext` remain unchanged. Read projection grants no permission to erase old physical values, refresh their TTL, recover a token or authorize a binding. Current raw-token cleanup, complete rotation/rebind/fencing and Account logout authority remain incomplete. + +Presence registration, cached read projection and ordinary activity updates use `PLAYER` because no independently verified gameplay-grant carrier exists. The unused gameplay-specific `SessionClaims` helpers and their JWT-to-gameplay shortcut are removed; ordinary control-plane privilege behavior is retained. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) records local storage and projection consequences, while [Player Experience](./player-experience-commands-and-communication.md#communication-social-and-presence) owns detailed WHO/presence status. R1423 executes 137 selected unit cases across Common Security and Game Session plus six real-Redis cases, with zero failures, errors or skips. Physical proof uses the production Redis serializer and commands to inspect all four context/index values, read-only legacy bytes and TTL, movement/effect exact retry, and all three retained-elevation read paths followed by ordinary activity demotion. First-party-context preservation remains unit-qualified; issuer/grant inputs are controlled. The initial aggregate fails only the new integration fixture’s mutable-long static checks; making per-case IDs immutable recovers all six physical executions plus enabled integration analysis, formatting and documentation. Earlier unit/main-analysis results retain their source attribution; this is not a complete service-suite pass. No production grant, issuer, registration, transcript cleanup, admission or activation is supplied. + ### Reconnect and Continuity For generic Telnet and WebSocket, reconnect uses current identity and current Account runtime membership/entitlement authority, not only a prior backend token. Revoked membership, removed realm access, unavailable tenant gameplay, stale runtime target, and failed authority reads fail closed as appropriate. Current implementation resolves the effective disconnected-resume window but does not enforce it in `PLAY`; backend authority unavailability remains retryable temporary-unavailable behavior. A fresh `LOOK` redraw is the current-state authority after successful resume or fresh fallback. Reconnect target behavior and proof requirements remain canonical in [Reconnection](../../architecture/system-architecture-reconnection.md). @@ -672,7 +678,7 @@ The auth/session/routing guardrail family is complete at its current bounded sea The current numeric-reader guardrail is: numeric identifiers still used by an implemented seam must be present, well-formed, and positive; opaque room ids remain textual. This is not the durable cross-boundary target. [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) makes durable cross-boundary account, tenant, game-instance, character, and version identities scoped UUIDs, so replacing current numeric forms and proving scope-qualified comparison remains tracked migration work. Malformed or contradictory JWT/signed-token claims reject before identity comparison; partial routing bundles are absent or rejected, never completed by fallback; malformed persisted replay state is ignored/rejected or terminalizes only its affected durable work item; and request validation occurs before replay lookup when malformed shape could otherwise be masked by a stored effect. Malformed persisted Automation tenant identity terminalizes only that work item rather than aborting the batch. Unexpected parser/runtime bugs are not mislabeled as auth failures. -This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The corrected presence classifier ignores global roles and uses explicit current-tenant gameplay roles; broader admission, grant-issuance, and capability qualification remains tracked in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence). Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. +This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and current presence projects only `PLAYER` until an independent gameplay-grant carrier exists. JWT global/scoped role claims and cached elevation supply no gameplay authority; broader admission, grant-issuance, and capability qualification remains tracked in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence). Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. Replay boundaries validate both read and write sides. The legacy Account connect-token cached-success path is no longer called: `/auth/connect-token` denies after bootstrap/scope validation before any replay read, token mint, or replay/session mutation. Public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. @@ -776,7 +782,7 @@ No competing target state is currently recorded. Future design discussion is req | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | | Account Service | Global accounts, credentials/challenges, memberships, canonical tenant roles, entitlements, non-public realm grants, account lifecycle, and explicit public-production JOIN; canonical gameplay connect-token production currently fails closed after bootstrap/scope validation | Account REST/gRPC APIs, including `/auth/bootstrap/join` and the local JOIN RPC; `/auth/connect-token` currently returns `AUTH_UNAVAILABLE` before cached-success replay, minting, or replay/session mutation; public Gateway exposure remains blocked, leave remains target-only, and Game Session text JOIN dispatch remains #2898 | -| Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, gameplay-elevated roles, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | +| Common Security | **Current:** JWT/signed-token claims, current-account and tenant access, control-plane privilege claims, legacy session attestation, current service-identity handling, and downstream caller authorization. **Target:** certificate-derived mTLS workload identity and method allowlists authorize services, while typed `PlayerExecutionContext` carries player scope | `JwtClaims`, `SessionClaims`, session-context helpers, target `PlayerExecutionContext`, certificate-derived mTLS caller identity, caller allowlists, and shared authorization checks; legacy attestation/service-identity code is implementation debt, not target player authority | | TCP Proxy | Telnet transport, hidden bootstrap envelope, bounded connection-local ordered input buffering during edge rebind, disconnect notification, and Telnet close taxonomy | Telnet bridge; `TelnetRoutingBundle`; Game Session `NotifyDisconnect` | | Spring Cloud Gateway | Trusted TCP Proxy handshake validation, stable edge socket/session id, upstream gameplay bridge and rebind; public first-party cookie admission and shared pod readiness currently fail closed pending canonical producer/replay/key qualification. The combined readiness hold withdraws both Gateway Service endpoint families; independent route-level Service readiness remains a pre-rollout gap. | `/ws/game/**`; `TrustedTcpProxyIdentity`; current first-party cookie denial and deployment qualification in [Gateway readiness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness) | | Game Session | Text parser/interpreter, generic login/play/logout, Redis session context, takeover/resume, gameplay presence, admission normalization, command/control-plane routing, and redraw; first-party signed-context/route/private-handle receiving sources are local preparation, while bare first-party LOGIN/PLAY deny before downstream effects; StartSession retains and rechecks the Account-compared owner tuple | Text-command protocol; WebSocket ingress; Game Session gRPC/control plane; Account and World/Entity calls; first-party context consequence in [Authentication and authorization](../../architecture/system-architecture-authentication.md#gateway-to-game-session-connect-context-normative); owner-tuple consequence in [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index c10198a927..0463a7ebc3 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. Game Session currently has no independently verified gameplay-grant carrier, so newly written and returned presence uses the ordinary `PLAYER` projection; retained elevated cache values are presented as `PLAYER` until an ordinary presence update replaces them. Read-side demotion does not persist a change or extend TTL. R1423 qualifies this bounded receiving projection, with the source and recovery limits recorded below. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. @@ -15,7 +15,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] - The [Social UUID preparation boundary](#communication-social-and-presence) temporarily rejects parent-issued numeric callers and has incompatible outbound peer readers; final supported UUID behavior is restored through #3360 and #2972, with service-local safety gaps still explicit. - Friend-presence reads still lack snapshot-bound pagination and bounded-page proof; complete these against the [Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract). - Friend-presence continuation still needs current friendship and block-state revalidation; complete this against the [Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#target-state-snapshot-chunking-pagination-and-failure-precedence). -- Production tenant-gameplay-grant qualification and broader runtime authorization/disclosure proof remain incomplete; focused presence classification proof does not establish admission or grant issuance under [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md). +- Game Session has no independently verified gameplay-grant carrier today, so presence currently uses `PLAYER`; the received correction has not yet had its focused proof executed on this head. Production tenant-gameplay-grant qualification, admission, and broader runtime authorization/disclosure proof remain incomplete under [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and the canonical [authentication owner](../../architecture/system-architecture-authentication.md). ## Capability Status @@ -24,9 +24,9 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | -| EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | +| EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | -| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `audited` - bounded ownership, correlation, role-classification, and player-disclosure corrections have focused source/test evidence; snapshot-bound pagination, current friendship/block revalidation, bounded-page proof, and production tenant-gameplay-grant qualification remain incomplete. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [RedisGameplayPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java); [RedisAccountRecentPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java); [AccountClient.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [RedisAccountRecentPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java); [AccountClientTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Complete snapshot-bound pagination, current relationship/block revalidation, bounded-page proof and production tenant-gameplay-grant qualification; keep in-world concealment under gameplay policy before calling this capability proven. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | +| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - previously recorded focused evidence remains attributed to its original sources; R1423 qualifies PLAYER-only creation/projection, cached-role read projection without persisting demotion or extending presence TTL, and ordinary field-preserving updates. Snapshot-bound pagination, current friendship/block revalidation, bounded-page proof, and production tenant-gameplay-grant qualification also remain incomplete. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [RedisGameplayPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java); [RedisAccountRecentPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java); [AccountClient.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [WhoCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java); [RedisAccountRecentPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java); [AccountClientTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Current Game Session has no independently verified gameplay-grant carrier, so new and returned presence uses `PLAYER`; JWT global/scoped claims and retained elevated cache roles do not elevate a presence projection. Read-side role demotion is projection-only and does not persist the role change or extend presence TTL; ordinary activity updates persist `PLAYER` while preserving the other presence fields. R1423 qualifies this bounded behavior through the Redis, WHO/reconnect units and real-Redis cases described below. Complete snapshot-bound pagination, current relationship/block revalidation, bounded-page proof, production tenant-gameplay-grant qualification, and broader authorization/disclosure proof remain open. Keep in-world concealment under gameplay policy before calling this capability proven. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | | EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, but this is not the independently released static player application boundary. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. No independently released static host/public-site routing or browser proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json) | No focused executable proof: `npm run lint` and `npm run build` from the [web-client package](../../../web-client/package.json) passed as general frontend validation and emitted the `dist/frontend-assets/` bundle, but no focused browser or independently released host proof exists. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, unprivileged static host and deployment, reserved-path routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | @@ -76,11 +76,11 @@ At this preparation stage, Social sends UUIDs to five outbound peer operations w Focused source proof covers complete Common Security and Social unit suites, native Social application cases, and seven physical PostgreSQL migration/repository cases preserving parent history and refusing populated legacy tables. Later selected proof covers mail caller refusal, Account response correlation and the access guard. The most recent complete unit tasks reused retained results rather than executing freshly; canonical schema, enabled analysis, formatting and documentation checks also pass. Exact run history, failures and recoveries remain in the review records. These separate proofs do not establish whole-composition or real-service gameplay safety. Current-head CI, independent review and fresh-image smoke remain separate obligations; production custody, registration, admission and activation holds remain with [Player Access and Session](./player-access-and-session.md#social-uuid-receiver-preparation). -- Focused unit, native application and WebSocket composition proof covers the bounded presence-owner correlation, tenant-scoped classification, profile-policy projection and player-facing output corrections. The concrete implementation and executable proof anchors are listed in EA-2.3 above; exact runs, retained results and failed/recovery attribution remain in the review records. These tests use controlled collaborators and do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and the [Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract) own the behavior. +- Previously recorded focused unit, native application and WebSocket composition evidence covers bounded presence-owner correlation, the earlier tenant-scoped classification, profile-policy projection and player-facing output corrections; its exact run attribution remains in the review records. The current receiving source changes make Game Session presence PLAYER-only while no independent gameplay-grant carrier is available, and add cached-role projection plus ordinary-update demotion. R1423 passes 137 selected Common/Game Session units, including Redis presence, WHO and reconnect cases, plus six actual-Redis cases using the production serializer. Its physical cache cases compare retained bytes and TTL through session, game and account reads before field-preserving activity demotion. The initial aggregate fails only new integration-fixture mutable-long analysis; immutable per-case IDs recover all six physical cases and enabled integration static analysis, formatting and documentation. Earlier unit/main-analysis results keep their source attribution; these scoped results do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md), the [authentication owner](../../architecture/system-architecture-authentication.md), and the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md) own the target behavior. - Guild creation/member lifecycle callbacks emit best-effort operational logs after commit, with no committed lifecycle event on rollback. This logging supplies no durable audit or delivery guarantee. Consolidated receiving R1137 passes all 109 Social unit cases and all 15 selected native application cases, including the 12 `GuildServiceImplTest` cases covering all four actions, commit-versus-rollback context and a scoped throwing-appender regression. Enabled affected main/test/integration analysis, formatting and documentation checks pass. This proves the local dispatch boundary and supported service seams, not durable audit, delivery guarantees or current published-head/fresh-image qualification. - Current behavior/proof: `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, mail APIs, friends, guild APIs, presence reads, privacy settings, recipient delivery, and speech normalization are live at bounded service/API seams; focused communication, social, presence, privacy, moderation, and cross-service tests cover those seams. - Local gaps linked to [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md) include offline `TELL`, profile-scoped `SHOUT`, richer topology/interception, type-specific history/acknowledgement, entity-owned social value/attachments, closed observer views, cross-pod delivery, first-party recipient presentation, and the canonical gameplay `WHISPER` recipient-scope migration. These ADR links identify gaps; they do not restate target policy. -- Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). The bounded role, legacy-policy and player-disclosure corrections above do not complete snapshot-bound continuation, broad activity consumers or production gameplay-grant proof. +- Presence/privacy drift remains tracked against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). Current `gameplaypresence:*` and `accountrecentpresence:*` Redis shapes, partial-write behavior, reset/readback behavior, storage role, and proof of private-by-failure enforcement for missing, stale, partial, or ambiguous evidence remain implementation/proof gaps. The canonical raw-presence/friend-projection ownership and disclosure rules are in the [Social & Groups Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract); canonical owner/reset details also live in the [Redis reset catalog](../../architecture/system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Current Game Session has no independent gameplay-grant carrier, so the received source defaults presence to `PLAYER`; the focused R1423 receiving proof does not establish production grant qualification. This correction does not complete snapshot-bound continuation, broad activity consumers, private-by-failure enforcement, or broader authorization/disclosure proof. ### First-Party Frontend diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 87381a7bac..6dbacaf48d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -74,23 +74,6 @@ public boolean hasPrivilegedRole() { return false; } - public boolean hasGameplayElevatedRole(String tenantId) { - if (containsAnyRoleIgnoreCase(globalRoles, "platformAdmin", "moderator", "god")) { - return true; - } - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), "tenantAdmin", "moderator", "god"); - } - - /** Returns whether a global or requested tenant-scoped role matches a gameplay role. */ - public boolean hasGameplayRole(String tenantId, String... expectedRoles) { - if (containsAnyRoleIgnoreCase(globalRoles, expectedRoles)) { - return true; - } - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), expectedRoles); - } - private static List extractGlobalRoles(Object rawGlobalRoles) { if (rawGlobalRoles == null) { return List.of(); @@ -132,22 +115,4 @@ private static List normalizeRoleValues(List values) { } return normalizedRoles; } - - private static boolean containsAnyRoleIgnoreCase( - Iterable roles, String... expectedRoles) { - if (roles == null) { - return false; - } - for (String role : roles) { - if (!StringUtils.hasText(role)) { - continue; - } - for (String expectedRole : expectedRoles) { - if (role.equalsIgnoreCase(expectedRole)) { - return true; - } - } - } - return false; - } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index ee682b0e38..21451e2463 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -110,37 +110,19 @@ private static Jws jwt(Claims payload) { } @Test - void hasGameplayElevatedRoleRecognizesGlobalGodAndScopedModerator() { - SessionClaims globalGod = - new SessionClaims("11", List.of("god"), Map.of("7", List.of("player")), false, null, null); - SessionClaims scopedModerator = - new SessionClaims("11", List.of(), Map.of("7", List.of("moderator")), false, null, null); - - assertTrue(globalGod.hasGameplayElevatedRole("7")); - assertTrue(scopedModerator.hasGameplayElevatedRole("7")); - } - - @Test - void hasGameplayElevatedRoleIgnoresUnrelatedTenantScopes() { + void hasPrivilegedRoleRecognizesGlobalControlPlaneRole() { SessionClaims claims = - new SessionClaims("11", List.of(), Map.of("8", List.of("tenantAdmin")), false, null, null); + new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); - assertFalse(claims.hasGameplayElevatedRole("7")); + assertTrue(claims.hasPrivilegedRole()); } @Test - void hasGameplayRoleChecksGlobalAndRequestedTenantScopeOnly() { + void hasPrivilegedRoleRecognizesTenantScopedControlPlaneRoles() { SessionClaims claims = new SessionClaims( - "11", - List.of("platformAdmin"), - Map.of("7", List.of("moderator"), "8", List.of("god")), - false, - null, - null); + "11", List.of(), Map.of("7", List.of("tenantAdmin", "moderator")), false, null, null); - assertTrue(claims.hasGameplayRole("7", "platformAdmin")); - assertTrue(claims.hasGameplayRole("7", "moderator")); - assertFalse(claims.hasGameplayRole("7", "god")); + assertTrue(claims.hasPrivilegedRole()); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 9b31c88226..a0d300a082 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -55,7 +55,7 @@ public ProbeResult probeSessionContextStore() { sessionContextService .findByTenantAndSessionId(PROBE_TENANT_ID, probeSessionId) .orElseThrow(() -> new IllegalStateException("session context was not persisted")); - if (!stored.equals(context)) { + if (!stored.equals(context.withoutJwt())) { return ProbeResult.down("stored session context did not round-trip"); } return ProbeResult.up("ROUND_TRIP_OK"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index e61bc220d6..38a26786eb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -319,6 +319,32 @@ private static String normalizeText(String text) { return text.trim(); } + /** Returns the non-secret Redis projection without changing this process-local context. */ + public SessionContext withoutJwt() { + if (jwt == null) { + return this; + } + return new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + characterId, + characterName, + gameInstanceId, + roomInstanceId, + null, + localeTag, + bootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + playableStateScope, + connectScopeId, + connectRequestId, + firstPartyConnectContext); + } + public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java deleted file mode 100644 index cb97af9402..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.firedevops.firemud.gamesession.service.impl; - -import io.jsonwebtoken.JwtException; -import java.util.List; -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.common.security.SessionClaims; -import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; -import org.springframework.util.StringUtils; - -final class GameplayPresenceRoleClassifier { - private GameplayPresenceRoleClassifier() {} - - static GameplayPresenceRole classifyRole(SessionContext context, JwtUtil jwtUtil, Logger logger) { - if (!StringUtils.hasText(context.jwt())) { - return GameplayPresenceRole.PLAYER; - } - try { - SessionClaims claims = SessionClaims.fromJwt(jwtUtil.parseToken(context.jwt())); - String tenantId = Long.toString(context.tenantId()); - List gameplayRoles = claims.scopedRoles().getOrDefault(tenantId, List.of()); - if (gameplayRoles.stream().anyMatch("god"::equalsIgnoreCase)) { - return GameplayPresenceRole.GOD; - } - if (gameplayRoles.stream().anyMatch("tenantAdmin"::equalsIgnoreCase)) { - return GameplayPresenceRole.ADMIN; - } - if (gameplayRoles.stream().anyMatch("moderator"::equalsIgnoreCase)) { - return GameplayPresenceRole.MODERATOR; - } - } catch (IllegalArgumentException | JwtException ex) { - logger.debug( - "Failed to classify WHO role from JWT for session {} tenant {}", - context.sessionId(), - context.tenantId(), - ex); - } - return GameplayPresenceRole.PLAYER; - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 3067fd2b96..875be79e44 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -12,7 +12,6 @@ import java.util.Set; import java.util.function.LongSupplier; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; @@ -47,24 +46,20 @@ public final class RedisGameplayPresenceService implements GameplayPresenceServi private final RedisTemplate redisTemplate; private final Duration presenceTtl; - private final JwtUtil jwtUtil; private final LongSupplier currentTimeMillisSupplier; @Autowired public RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, @Value("${FIREMUD_AUTH_SESSION_EXPIRATION_MS:3600000}") long sessionExpirationMs) { - this(redisTemplate, jwtUtil, sessionExpirationMs, System::currentTimeMillis); + this(redisTemplate, sessionExpirationMs, System::currentTimeMillis); } RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, long sessionExpirationMs, LongSupplier currentTimeMillisSupplier) { this.redisTemplate = redisTemplate; - this.jwtUtil = jwtUtil; this.presenceTtl = Duration.ofMillis(sessionExpirationMs); this.currentTimeMillisSupplier = currentTimeMillisSupplier; } @@ -96,7 +91,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - classifyRole(context), + GameplayPresenceRole.PLAYER, currentTimeMillisSupplier.getAsLong(), null, null, @@ -137,28 +132,29 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { if (existing == null) { return; } + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), explicitAfk ? Long.valueOf(currentTimeMillisSupplier.getAsLong()) : null, - existing.lastAcceptedCommandAtEpochMs(), - existing.lastMeaningfulActivityAtEpochMs()); + current.lastAcceptedCommandAtEpochMs(), + current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - if (StringUtils.hasText(existing.accountId())) { - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + if (StringUtils.hasText(current.accountId())) { + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } } @@ -170,30 +166,31 @@ public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActi return; } long now = currentTimeMillisSupplier.getAsLong(); + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), - existing.explicitAfkSinceEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), + current.explicitAfkSinceEpochMs(), Long.valueOf(now), meaningfulGameplayActivity ? Long.valueOf(now) - : existing.lastMeaningfulActivityAtEpochMs()); + : current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - if (StringUtils.hasText(existing.accountId())) { - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + if (StringUtils.hasText(current.accountId())) { + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } } @@ -229,7 +226,7 @@ public List listConnectedByGameInstance(long tenantId, long ga continue; } if (presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) { - matches.add(presence); + matches.add(playerPresence(presence)); } } @@ -290,7 +287,7 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - accountMatches.add(presence); + accountMatches.add(playerPresence(presence)); } if (!accountMatches.isEmpty()) { accountMatches.sort(ACCOUNT_PRESENCE_PREFERENCE.reversed()); @@ -305,12 +302,35 @@ public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); try { return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) - .filter(presence -> SessionContext.isCanonicalAccountIdentity(presence.accountId())); + .filter(presence -> SessionContext.isCanonicalAccountIdentity(presence.accountId())) + .map(RedisGameplayPresenceService::playerPresence); } catch (SerializationException | ClassCastException ex) { return Optional.empty(); } } + private static GameplayPresence playerPresence(GameplayPresence presence) { + if (presence.role() == GameplayPresenceRole.PLAYER) { + return presence; + } + return new GameplayPresence( + presence.sessionId(), + presence.tenantId(), + presence.gameInstanceId(), + presence.playableStateScope(), + presence.worldSlug(), + presence.realmSlug(), + presence.pointerVersion(), + presence.accountId(), + presence.characterId(), + presence.characterName(), + GameplayPresenceRole.PLAYER, + presence.connectedAtEpochMs(), + presence.explicitAfkSinceEpochMs(), + presence.lastAcceptedCommandAtEpochMs(), + presence.lastMeaningfulActivityAtEpochMs()); + } + private String presenceKey(long sessionId) { return String.format(PRESENCE_KEY_TEMPLATE, sessionId); } @@ -347,10 +367,6 @@ private String accountKey(long tenantId, String accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } - private GameplayPresenceRole classifyRole(SessionContext context) { - return GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger); - } - private String fallbackCharacterName(SessionContext context) { if (StringUtils.hasText(context.loginName())) { return context.loginName().trim(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java index 2fdc1cc038..297fd089fd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java @@ -92,7 +92,7 @@ public MoveEffectApplyResult execute( operations.multi(); deleteIndexes(operations, current); writeContext(operations, updated); - operations.opsForValue().set(effectKey, updated, sessionTtl); + operations.opsForValue().set(effectKey, updated.withoutJwt(), sessionTtl); if (operations.exec() != null) { return new MoveEffectApplyResult(MoveEffectApplyStatus.APPLIED, updated); } @@ -116,7 +116,7 @@ private SessionContext updateRoom(SessionContext current, String destinationRoom current.characterName(), current.gameInstanceId(), destinationRoomInstanceId, - current.jwt(), + null, current.localeTag(), current.bootstrapGameInstanceId(), current.worldSlug(), @@ -142,7 +142,8 @@ private String normalizeRoom(String roomId) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + SessionContext context = (SessionContext) operations.opsForValue().get(key); + return context == null ? null : context.withoutJwt(); } private void addWatchKeys(LinkedHashSet watchKeys, SessionContext context) { @@ -186,23 +187,32 @@ private void deleteIndexes( private void writeContext( org.springframework.data.redis.core.RedisOperations operations, SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); var ops = operations.opsForValue(); ops.set( - SessionContextRedisKeys.contextKey(context.tenantId(), context.sessionId()), - context, + SessionContextRedisKeys.contextKey( + persistedContext.tenantId(), persistedContext.sessionId()), + persistedContext, sessionTtl); - ops.set(SessionContextRedisKeys.sessionKey(context.sessionId()), context, sessionTtl); - if (context.hasGameplayIdentity()) { + ops.set( + SessionContextRedisKeys.sessionKey(persistedContext.sessionId()), + persistedContext, + sessionTtl); + if (persistedContext.hasGameplayIdentity()) { ops.set( SessionContextRedisKeys.identityKey( - context.tenantId(), context.gameInstanceId(), context.characterId()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId()), + persistedContext, sessionTtl); - if (hasGameplayName(context)) { + if (hasGameplayName(persistedContext)) { ops.set( SessionContextRedisKeys.nameKey( - context.tenantId(), context.gameInstanceId(), context.characterName()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName()), + persistedContext, sessionTtl); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index 7a765efaa7..38bc9e03d6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -221,7 +221,7 @@ private SessionContext readContext( throw new SessionContextUnavailableException( "Retained session context has a non-canonical Account identity", null); } - return context; + return context == null ? null : context.withoutJwt(); } private Optional findContextForLookup(String key) { @@ -231,7 +231,7 @@ private Optional findContextForLookup(String key) { throw new SessionContextUnavailableException( "Retained session context has a non-canonical Account identity", null); } - return Optional.ofNullable(context); + return Optional.ofNullable(context).map(SessionContext::withoutJwt); } catch (SerializationException | ClassCastException ex) { throw new SessionContextUnavailableException("Retained session context is unreadable", ex); } @@ -274,18 +274,28 @@ private void deleteIndexes( private void writeContext( org.springframework.data.redis.core.RedisOperations operations, SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); var ops = operations.opsForValue(); - ops.set(contextKey(context.tenantId(), context.sessionId()), context, sessionTtl); - ops.set(sessionKey(context.sessionId()), context, sessionTtl); - if (context.hasGameplayIdentity()) { + ops.set( + contextKey(persistedContext.tenantId(), persistedContext.sessionId()), + persistedContext, + sessionTtl); + ops.set(sessionKey(persistedContext.sessionId()), persistedContext, sessionTtl); + if (persistedContext.hasGameplayIdentity()) { ops.set( - identityKey(context.tenantId(), context.gameInstanceId(), context.characterId()), - context, + identityKey( + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId()), + persistedContext, sessionTtl); - if (StringUtils.hasText(context.characterName())) { + if (StringUtils.hasText(persistedContext.characterName())) { ops.set( - nameKey(context.tenantId(), context.gameInstanceId(), context.characterName()), - context, + nameKey( + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName()), + persistedContext, sessionTtl); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java new file mode 100644 index 0000000000..7d7864ce0a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java @@ -0,0 +1,314 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.RedisProperties; +import net.firedevops.firemud.gamesession.service.GameplayPresence; +import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; +import net.firedevops.firemud.gamesession.service.MovementEffectIdempotencyService.MoveEffectApplyStatus; +import net.firedevops.firemud.gamesession.service.SessionContext; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical containment proof with controlled records, not issuer, grant or admission authority. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class SessionContextSecretAndPresenceRedisIntegrationTest { + private static final String ACCOUNT = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; + private static final String RAW_JWT = "private-delegation-jwt-must-remain-process-local"; + private static final Duration STORE_TTL = Duration.ofMinutes(2); + private static final Duration RETAINED_TTL = Duration.ofSeconds(20); + private static final AtomicLong SEQUENCE = new AtomicLong(90_000L); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private final List ownedKeys = new ArrayList<>(); + private LettuceConnectionFactory connectionFactory; + private RedisTemplate template; + private RedisSessionContextService sessions; + private RedisMovementEffectIdempotencyService movement; + private final long sessionId = SEQUENCE.incrementAndGet(); + private final long gameInstanceId = sessionId + 1_000L; + private final long characterId = sessionId + 2_000L; + + @BeforeEach + void setUp() { + connectionFactory = + new LettuceConnectionFactory( + new RedisStandaloneConfiguration(REDIS.getHost(), REDIS.getMappedPort(6379))); + connectionFactory.afterPropertiesSet(); + template = + new DatabaseAutoConfiguration(new PostgresProperties(), new RedisProperties()) + .redisTemplate(connectionFactory); + template.afterPropertiesSet(); + sessions = new RedisSessionContextService(template, STORE_TTL.toMillis()); + movement = new RedisMovementEffectIdempotencyService(template, STORE_TTL.toMillis()); + ownedKeys.addAll(contextKeys()); + ownedKeys.add(effectKey()); + ownedKeys.add(presenceKey()); + ownedKeys.add(gamePresenceKey()); + ownedKeys.add(accountPresenceKey()); + } + + @AfterEach + void tearDown() { + try { + if (template != null) { + // Only this case's exact keys; no database-wide cleanup or shared Redis ownership. + template.delete(ownedKeys); + } + } finally { + if (connectionFactory != null) { + connectionFactory.destroy(); + } + } + } + + @Test + void canonicalAndIndexWritesPhysicallyPersistOnlyTheNoSecretProjection() { + SessionContext original = context("R-1021"); + + sessions.save(original); + + for (String key : contextKeys()) { + assertStoredContext(key, original.withoutJwt()); + assertThat(remainingTtl(key)).isPositive().isLessThanOrEqualTo(STORE_TTL.toMillis()); + } + assertThat(original.jwt()).isEqualTo(RAW_JWT); + } + + @Test + void allFourLegacyLookupsScrubOnlyReturnedValuesWithoutChangingBytesOrExtendingTtl() { + SessionContext legacy = context("R-1021"); + for (String key : contextKeys()) { + // Seed actual legacy serialization, bypassing the corrected writer intentionally. + template.opsForValue().set(key, legacy, RETAINED_TTL); + assertThat(new String(rawValue(key), StandardCharsets.ISO_8859_1)).contains(RAW_JWT); + } + Map retained = snapshot(contextKeys()); + + assertThat(sessions.findByTenantAndSessionId(42L, sessionId)).contains(legacy.withoutJwt()); + assertThat(sessions.findBySessionId(sessionId)).contains(legacy.withoutJwt()); + assertThat(sessions.findByGameplayIdentity(42L, gameInstanceId, characterId)) + .contains(legacy.withoutJwt()); + assertThat(sessions.findByGameplayName(42L, gameInstanceId, "Player")) + .contains(legacy.withoutJwt()); + + assertRetainedUnchanged(retained); + for (String key : contextKeys()) { + assertThat(template.opsForValue().get(key)).isEqualTo(legacy); + } + } + + @Test + void movementAndEffectWritesScrubLegacyJwtAndExactRetryPreservesPhysicalValuesAndTtl() { + SessionContext legacy = context("R-1021"); + for (String key : contextKeys()) { + template.opsForValue().set(key, legacy, RETAINED_TTL); + } + + var applied = movement.apply("physical-move", legacy, "R-2045"); + + assertThat(applied.status()).isEqualTo(MoveEffectApplyStatus.APPLIED); + SessionContext expected = context("R-2045").withoutJwt(); + assertThat(applied.context()).isEqualTo(expected); + List writtenKeys = new ArrayList<>(contextKeys()); + writtenKeys.add(effectKey()); + for (String key : writtenKeys) { + assertStoredContext(key, expected); + // A shorter real deadline makes any retry refresh to the writer TTL observable. + assertThat(template.expire(key, RETAINED_TTL)).isTrue(); + } + Map retained = snapshot(writtenKeys); + + var replayed = movement.apply("physical-move", legacy, "R-2045"); + + assertThat(replayed.status()).isEqualTo(MoveEffectApplyStatus.REPLAYED); + assertThat(replayed.context()).isEqualTo(expected); + assertRetainedUnchanged(retained); + assertThat(legacy.jwt()).isEqualTo(RAW_JWT); + } + + @ParameterizedTest + @EnumSource( + value = GameplayPresenceRole.class, + names = {"GOD", "ADMIN", "MODERATOR"}) + void retainedElevationReadsProjectPlayerWithoutMutationAndActivityStoresPlayer( + GameplayPresenceRole retainedRole) { + GameplayPresence legacy = presence(retainedRole, 1_200L, 1_300L); + template.opsForValue().set(presenceKey(), legacy, RETAINED_TTL); + template.opsForSet().add(gamePresenceKey(), Long.toString(sessionId)); + template.opsForSet().add(accountPresenceKey(), Long.toString(sessionId)); + assertThat(template.expire(gamePresenceKey(), RETAINED_TTL)).isTrue(); + assertThat(template.expire(accountPresenceKey(), RETAINED_TTL)).isTrue(); + Map retained = snapshot(List.of(presenceKey())); + long gameIndexTtl = remainingTtl(gamePresenceKey()); + long accountIndexTtl = remainingTtl(accountPresenceKey()); + var presence = new RedisGameplayPresenceService(template, STORE_TTL.toMillis(), () -> 9_000L); + GameplayPresence projected = presence(GameplayPresenceRole.PLAYER, 1_200L, 1_300L); + + assertThat(presence.findConnectedBySessionId(sessionId)).contains(projected); + assertThat(presence.listConnectedByGameInstance(42L, gameInstanceId)) + .containsExactly(projected); + assertThat(presence.listConnectedByAccountIds(42L, List.of(ACCOUNT))) + .containsExactlyEntriesOf(Map.of(ACCOUNT, List.of(projected))); + + assertRetainedUnchanged(retained); + assertThat(template.opsForValue().get(presenceKey())).isEqualTo(legacy); + assertThat(remainingTtl(gamePresenceKey())).isPositive().isLessThanOrEqualTo(gameIndexTtl); + assertThat(remainingTtl(accountPresenceKey())) + .isPositive() + .isLessThanOrEqualTo(accountIndexTtl); + assertThat(template.opsForSet().members(gamePresenceKey())) + .containsExactly(Long.toString(sessionId)); + assertThat(template.opsForSet().members(accountPresenceKey())) + .containsExactly(Long.toString(sessionId)); + + presence.recordCommandActivity(sessionId, true); + + assertThat(template.opsForValue().get(presenceKey())) + .isEqualTo(presence(GameplayPresenceRole.PLAYER, 9_000L, 9_000L)); + assertThat(remainingTtl(presenceKey())).isGreaterThan(RETAINED_TTL.toMillis()); + } + + private SessionContext context(String room) { + return new SessionContext( + sessionId, + 42L, + ACCOUNT, + "player@example.com", + characterId, + "Player", + gameInstanceId, + room, + RAW_JWT, + "fr", + gameInstanceId, + "demo", + "production", + 7L, + "SHARED", + "retained-scope", + "retained-request"); + } + + private GameplayPresence presence(GameplayPresenceRole role, long accepted, long meaningful) { + return new GameplayPresence( + sessionId, + 42L, + gameInstanceId, + "SHARED", + "demo", + "production", + 7L, + ACCOUNT, + characterId, + "Player", + role, + 1_000L, + 1_100L, + accepted, + meaningful); + } + + private List contextKeys() { + return List.of( + SessionContextRedisKeys.contextKey(42L, sessionId), + SessionContextRedisKeys.sessionKey(sessionId), + SessionContextRedisKeys.identityKey(42L, gameInstanceId, characterId), + SessionContextRedisKeys.nameKey(42L, gameInstanceId, "Player")); + } + + private String effectKey() { + return SessionContextRedisKeys.movementEffectKey(42L, sessionId, "physical-move"); + } + + private String presenceKey() { + return "gameplaypresence:session:" + sessionId; + } + + private String gamePresenceKey() { + return "gameplaypresence:42:" + gameInstanceId + ":sessions"; + } + + private String accountPresenceKey() { + return "gameplaypresence:42:account:" + ACCOUNT + ":sessions"; + } + + private void assertStoredContext(String key, SessionContext expected) { + assertThat(template.opsForValue().get(key)).isEqualTo(expected); + assertThat(new String(rawValue(key), StandardCharsets.ISO_8859_1)).doesNotContain(RAW_JWT); + } + + private Map snapshot(List keys) { + Map retained = new LinkedHashMap<>(); + for (String key : keys) { + long ttl = remainingTtl(key); + assertThat(ttl).isPositive(); + retained.put(key, new RetainedValue(rawValue(key), ttl)); + } + return retained; + } + + private void assertRetainedUnchanged(Map retained) { + retained.forEach( + (key, value) -> { + assertThat(rawValue(key)).containsExactly(value.bytes()); + assertThat(remainingTtl(key)).isPositive().isLessThanOrEqualTo(value.ttlMillis()); + }); + } + + private long remainingTtl(String key) { + return Objects.requireNonNull(template.getExpire(key, TimeUnit.MILLISECONDS)); + } + + private byte[] rawValue(String key) { + byte[] serializedKey = serializedKey(key); + return Objects.requireNonNull( + template.execute( + (RedisCallback) connection -> connection.stringCommands().get(serializedKey))); + } + + @SuppressWarnings("unchecked") + private byte[] serializedKey(String key) { + return Objects.requireNonNull( + ((RedisSerializer) Objects.requireNonNull(template.getKeySerializer())) + .serialize(key)); + } + + private record RetainedValue(byte[] bytes, long ttlMillis) { + private RetainedValue { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } +} diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index cdb8c9dadd..7af02dc9a4 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -10,23 +10,15 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; +import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; import org.springframework.util.StringUtils; /** Small process-local fake for command tests; production presence is Redis-backed. */ public final class FakeGameplayPresenceService implements GameplayPresenceService { - private static final Logger logger = LoggingUtil.getLogger(FakeGameplayPresenceService.class); private final ConcurrentMap presences = new ConcurrentHashMap<>(); - private final JwtUtil jwtUtil; - - public FakeGameplayPresenceService(JwtUtil jwtUtil) { - this.jwtUtil = jwtUtil; - } @Override public void registerConnected(SessionContext context) { @@ -48,7 +40,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger), + GameplayPresenceRole.PLAYER, System.currentTimeMillis(), null, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index da3f685796..7d76a692ad 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -57,6 +57,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceActivityResolver; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; @@ -125,8 +126,9 @@ class SessionResumptionFlowTest { private final HelpCommandHandler helpHandler = new HelpCommandHandler(); private final CommunicationCommandHandler communicationHandler = Mockito.mock(CommunicationCommandHandler.class); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + private final JwtUtil gameplayJwtUtil = + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, @@ -642,6 +644,36 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI null); } + @Test + void freshScopedAndGlobalRoleClaimsDoNotElevatePresenceAcrossReconnect() { + String jwt = + gameplayJwtUtil.generateToken( + ACCOUNT_ID, + Map.of( + "accountId", + ACCOUNT_ID, + "globalRoles", + List.of("platformAdmin", "support", "billingAdmin"), + "scopedRoles", + Map.of("22", List.of("god", "tenantAdmin", "moderator")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(jwt).setAccountId(ACCOUNT_ID).build()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + assertEquals(1.0, meterRegistry.counter("gamesession.session.resume").count()); + } + private static final class InMemorySessionContextService implements SessionContextService { private final Map sessionMap = new ConcurrentHashMap<>(); private final Map identityMap = new ConcurrentHashMap<>(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 7fc3bb6793..d2a3432b95 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -26,7 +26,6 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; import net.firedevops.firemud.entitymanagement.v1.EquipmentItem; @@ -143,8 +142,7 @@ class TextCommandInterpreterTest { PresentationProperties.ColorMode.NONE, false, new PresentationProperties.Prompt(true, true, 150L))); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 42619de5ed..08445c1fc2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -26,7 +26,7 @@ class WhoCommandHandlerTest { @Test void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -49,8 +49,8 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { } @Test - void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + void whoPresentsJwtRoleClaimSessionsAsPlayersWithoutGrantEvidence() { + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String godJwt = @@ -59,8 +59,6 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { java.util.Map.of( "accountId", net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(1L), - "globalRoles", - java.util.List.of("platformAdmin"), "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); @@ -85,13 +83,13 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { GameplayPresenceTestFixtures.whoBen("second@example.com")); assertThat(result.commandResult().accepted()).isTrue(); - assertThat(render(result)).isEqualTo("Gods [2]: Aster, Dara\nPlayers [2]: Ben, Cara"); + assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [4]: Aster, Ben, Cara, Dara"); } @Test void normallyJoinedGlobalStaffAppearsAsAnOrdinaryPlayer() { for (String role : java.util.List.of("platformAdmin", "support", "billingAdmin", "god")) { - FakeGameplayPresenceService presence = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService presence = new FakeGameplayPresenceService(); String token = jwtUtil.generateToken( GameplayPresenceTestFixtures.whoAster("staff@example.com", null).accountId(), @@ -113,7 +111,7 @@ void normallyJoinedGlobalStaffAppearsAsAnOrdinaryPlayer() { @Test void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -134,7 +132,7 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { @Test void whoAnnotatesExplicitAndAutoAfkPlayers() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); GameplayPresenceActivityResolver resolver = Mockito.mock(GameplayPresenceActivityResolver.class); WhoCommandHandler handler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 27892167f1..0178c156d0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -46,7 +46,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, - "readiness-probe")); + null)); }); GameplayLocalPathReadinessProbe probe = @@ -102,11 +102,37 @@ void sessionContextProbeUsesCanonicalAccountIdentityAcceptedByRedisLookup() { assertEquals(UUID.fromString(savedContext.accountId()).toString(), savedContext.accountId()); assertTrue(savedContext.hasAccountIdentity()); assertEquals( - Optional.of(savedContext), + Optional.of(savedContext.withoutJwt()), strictLookup.findByTenantAndSessionId(savedContext.tenantId(), savedContext.sessionId())); verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); } + @Test + void sessionContextProbeRejectsStoredRawJwtAndStillOwnsOnlyItsCanaryCleanup() { + SessionContextService sessionContextService = mock(SessionContextService.class); + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = mock(RedisTemplate.class); + doAnswer( + invocation -> { + SessionContext context = invocation.getArgument(0, SessionContext.class); + when(sessionContextService.findByTenantAndSessionId(0L, context.sessionId())) + .thenReturn(Optional.of(context)); + return null; + }) + .when(sessionContextService) + .save(any(SessionContext.class)); + + ProbeResult result = + new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate) + .probeSessionContextStore(); + + assertEquals(false, result.ready()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + verify(sessionContextService).deleteBySessionId(0L, captor.getValue().sessionId()); + verify(redisTemplate, never()).delete(anyString()); + } + @Test void commandQueueProbeReturnsUpWhenQueueWriteRoundTrips() { SessionContextService sessionContextService = mock(SessionContextService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java deleted file mode 100644 index d994e704e4..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.firedevops.firemud.gamesession.service.impl; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; - -class GameplayPresenceRoleClassifierTest { - private static final JwtUtil JWT_UTIL = new JwtUtil("mysecretkey123456789012345678901", 30_000L); - private static final String ACCOUNT_UUID = "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1"; - - @Test - void classifyRoleReturnsPlayerWhenJwtParserThrowsIllegalArgumentException() { - JwtUtil jwtUtil = mock(JwtUtil.class); - Logger logger = mock(Logger.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalArgumentException("bad jwt")); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), - jwtUtil, - logger); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleReturnsModeratorForScopedModeratorRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of( - "accountId", - ACCOUNT_UUID, - "scopedRoles", - java.util.Map.of("22", java.util.List.of("moderator")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.MODERATOR, role); - } - - @Test - void classifyRoleIgnoresGlobalGodRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of("accountId", ACCOUNT_UUID, "globalRoles", java.util.List.of("god"))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleReturnsAdminForTenantAdminRole() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of( - "accountId", - ACCOUNT_UUID, - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.ADMIN, role); - } - - @Test - void classifyRoleDoesNotLetGlobalRolesOverrideTheTenantGrant() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of( - "accountId", - ACCOUNT_UUID, - "globalRoles", - java.util.List.of("moderator", "god"), - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.ADMIN, role); - } - - @Test - void classifyRoleIgnoresGlobalOperationsAndOtherTenants() { - for (String globalRole : - java.util.List.of("platformAdmin", "support", "billingAdmin", "moderator", "tenantAdmin")) { - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of( - "accountId", - ACCOUNT_UUID, - "globalRoles", - java.util.List.of(globalRole), - "scopedRoles", - java.util.Map.of("23", java.util.List.of("god")))); - assertEquals( - GameplayPresenceRole.PLAYER, - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - mock(Logger.class))); - } - } - - @Test - void classifyRoleUsesTheHighestExplicitCurrentTenantGrant() { - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, - java.util.Map.of( - "accountId", - ACCOUNT_UUID, - "scopedRoles", - java.util.Map.of("22", java.util.List.of("moderator", "tenantAdmin", "GOD")))); - assertEquals( - GameplayPresenceRole.GOD, - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - mock(Logger.class))); - } - - @Test - void classifyRoleReturnsPlayerWhenScopedRolesClaimIsMalformed() { - Logger logger = mock(Logger.class); - String jwt = - JWT_UTIL.generateToken( - ACCOUNT_UUID, java.util.Map.of("accountId", ACCOUNT_UUID, "scopedRoles", "bad")); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, ACCOUNT_UUID, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - logger); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 3a7acd66bc..d7fe7e55e8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -43,7 +43,7 @@ class RedisGameplayPresenceServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.opsForSet()).thenReturn(setOperations); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis()); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis()); } @Test @@ -92,7 +92,7 @@ void registerAndQueryRejectNonCanonicalAccountIdsWithoutPresenceMutation() { } @Test - void registerConnectedClassifiesInvalidJwtAsPlayer() { + void registerConnectedStoresPlayerForInvalidJwt() { SessionContext context = new SessionContext( 1L, 22L, PLAYER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); @@ -138,22 +138,33 @@ void registerConnectedKeepsGlobalStaffInThePlayerRole() { } @Test - void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { - String godJwt = + void registerConnectedDoesNotPromoteScopedJwtRolesWithoutGameplayGrantEvidence() { + String token = jwtUtil.generateToken( - GOD_ACCOUNT_ID, + OTHER_ACCOUNT_ID, Map.of( "accountId", - GOD_ACCOUNT_ID, - "globalRoles", - List.of("platformAdmin"), + OTHER_ACCOUNT_ID, "scopedRoles", - Map.of("22", List.of("god")))); - SessionContext godContext = + Map.of("22", List.of("god", "tenantAdmin", "moderator")))); + service.registerConnected( new SessionContext( - 1L, 22L, GOD_ACCOUNT_ID, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); - service.registerConnected(godContext); + 1L, 22L, OTHER_ACCOUNT_ID, "player@example.com", 202L, "Ben", 7L, "R-1", token)); + verify(valueOperations) + .set( + org.mockito.Mockito.eq("gameplaypresence:session:1"), + argThat( + value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), + org.mockito.Mockito.eq(TTL)); + } + + @Test + void listConnectedByGameInstanceDemotesCachedElevationAndPrunesMissingSessions() { when(setOperations.members("gameplaypresence:22:7:sessions")) .thenReturn(new LinkedHashSet<>(List.of("1", "2"))); when(valueOperations.get("gameplaypresence:session:1")) @@ -162,24 +173,35 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 1L, 22L, 7L, + "SHARED", "demo", "production", + 17L, GOD_ACCOUNT_ID, 101L, "Aster", GameplayPresenceRole.GOD, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); when(valueOperations.get("gameplaypresence:session:2")).thenReturn(null); var result = service.listConnectedByGameInstance(22L, 7L); assertEquals(1, result.size()); - assertEquals(GameplayPresenceRole.GOD, result.get(0).role()); + assertEquals(GameplayPresenceRole.PLAYER, result.get(0).role()); assertEquals("Aster", result.get(0).characterName()); + assertEquals("SHARED", result.get(0).playableStateScope()); + assertEquals(17L, result.get(0).pointerVersion()); + assertEquals(50L, result.get(0).explicitAfkSinceEpochMs()); + assertEquals(60L, result.get(0).lastAcceptedCommandAtEpochMs()); + assertEquals(65L, result.get(0).lastMeaningfulActivityAtEpochMs()); verify(setOperations).remove("gameplaypresence:22:7:sessions", "2"); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test @@ -197,7 +219,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { GOD_ACCOUNT_ID, 101L, "Aster", - GameplayPresenceRole.GOD, + GameplayPresenceRole.PLAYER, 70L, null, null, @@ -218,8 +240,10 @@ void removeBySessionIdRemovesValueAndSetMembership() { 3L, 22L, 7L, + "ISOLATED", "demo", "production", + 17L, PLAYER_ACCOUNT_ID, 202L, "Ben", @@ -238,50 +262,70 @@ void removeBySessionIdRemovesValueAndSetMembership() { } @Test - void findConnectedBySessionIdReadsPresenceRecordDirectly() { + void findConnectedBySessionIdProjectsCachedElevationWithoutWritingOrRefreshingTtl() { when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( 4L, 22L, 7L, + "SHARED", "demo", "production", + 17L, OTHER_ACCOUNT_ID, 102L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); var presence = service.findConnectedBySessionId(4L); assertEquals(true, presence.isPresent()); assertEquals(4L, presence.get().sessionId()); + assertEquals(GameplayPresenceRole.PLAYER, presence.get().role()); + assertEquals(22L, presence.get().tenantId()); + assertEquals(7L, presence.get().gameInstanceId()); + assertEquals("SHARED", presence.get().playableStateScope()); + assertEquals(OTHER_ACCOUNT_ID, presence.get().accountId()); + assertEquals(102L, presence.get().characterId()); + assertEquals("Ben", presence.get().characterName()); + assertEquals(17L, presence.get().pointerVersion()); + assertEquals(70L, presence.get().connectedAtEpochMs()); + assertEquals(50L, presence.get().explicitAfkSinceEpochMs()); + assertEquals(60L, presence.get().lastAcceptedCommandAtEpochMs()); + assertEquals(65L, presence.get().lastMeaningfulActivityAtEpochMs()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( 3L, 22L, 7L, + "ISOLATED", "demo", "production", + 17L, PLAYER_ACCOUNT_ID, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, - null, - null, - null)); + 95L, + 99L, + 90L)); now.set(125L); service.recordCommandActivity(3L, false); @@ -292,6 +336,15 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest argThat( value -> value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .accountId() + .equals(PLAYER_ACCOUNT_ID) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .playableStateScope() + .equals("ISOLATED") + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .pointerVersion() + == 17L && Long.valueOf(125L) .equals( ((net.firedevops.firemud.gamesession.service.GameplayPresence) @@ -299,7 +352,10 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest .lastAcceptedCommandAtEpochMs()) && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) .lastMeaningfulActivityAtEpochMs() - == null), + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate) @@ -309,23 +365,25 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest @Test void setExplicitAfkRefreshesPresenceRecord() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( 3L, 22L, 7L, + "ISOLATED", "demo", "production", + 17L, PLAYER_ACCOUNT_ID, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.MODERATOR, 80L, - null, - null, - null)); + 85L, + 90L, + 95L)); now.set(145L); service.setExplicitAfk(3L, true); @@ -336,11 +394,29 @@ void setExplicitAfkRefreshesPresenceRecord() { argThat( value -> value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .accountId() + .equals(PLAYER_ACCOUNT_ID) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .playableStateScope() + .equals("ISOLATED") + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .pointerVersion() + == 17L && Long.valueOf(145L) .equals( ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .explicitAfkSinceEpochMs())), + .explicitAfkSinceEpochMs()) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastAcceptedCommandAtEpochMs() + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastMeaningfulActivityAtEpochMs() + == 95L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate) @@ -364,7 +440,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { PLAYER_ACCOUNT_ID, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, null, 100L, @@ -382,7 +458,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { PLAYER_ACCOUNT_ID, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.GOD, 90L, null, 110L, @@ -392,8 +468,16 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { assertEquals(1, result.size()); assertEquals(2, result.get(PLAYER_ACCOUNT_ID).size()); + assertEquals( + true, + result.get(PLAYER_ACCOUNT_ID).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); assertEquals(4L, result.get(PLAYER_ACCOUNT_ID).get(0).sessionId()); assertEquals(3L, result.get(PLAYER_ACCOUNT_ID).get(1).sessionId()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index 6a39fb10fa..c7db98e6f8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; @@ -51,7 +53,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { new SessionContext( 41L, 22L, - "123", + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo@example.com", 7001L, "demo", @@ -74,6 +76,9 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { SessionContext updated = result.context(); assertNotNull(updated); assertEquals("R-2045", updated.roomInstanceId()); + assertNull(updated.jwt()); + assertEquals("jwt-token", current.jwt()); + assertFalse(SessionContextSerializationTestSupport.serialize(updated).contains(current.jwt())); assertEquals(retainedContext, updated.firstPartyConnectContext()); assertEquals("demo", updated.worldSlug()); assertEquals("production", updated.realmSlug()); @@ -94,7 +99,7 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(current, result.context()); + assertEquals(current.withoutJwt(), result.context()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } @@ -109,11 +114,30 @@ void applyReturnsReplayedContextWhenReplayAlreadyStored() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.REPLAYED, result.status()); - assertEquals(replayed, result.context()); + assertEquals(replayed.withoutJwt(), result.context()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } + @Test + void replayProjectsSerializedLegacyJwtOutWithoutWritingOrRefreshingRedis() { + SessionContext current = baselineContext(); + SessionContext legacyReplay = + SessionContextSerializationTestSupport.roundTrip(withRoom(current, "R-2045")); + when(valueOperations.get("sessionctx:22:41:context")).thenReturn(current); + when(valueOperations.get("sessionctx:22:41:movement-effect:tfx-1")).thenReturn(legacyReplay); + + MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); + + assertEquals(MoveEffectApplyStatus.REPLAYED, result.status()); + assertEquals(legacyReplay.withoutJwt(), result.context()); + assertEquals("jwt-token", legacyReplay.jwt()); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).delete(anyString()); + verify(redisTemplate, never()).expire(anyString(), any(Duration.class)); + verify(redisTemplate, never()).multi(); + } + @Test void applyRejectsLegacyExpectedRoomBeforeRedisLookup() { SessionContext legacyExpected = withRoom(baselineContext(), "room-1021"); @@ -133,7 +157,7 @@ void applyRejectsLegacyStoredCurrentRoomBeforeWrite() { MoveEffectApplyResult result = service.apply("tfx-1", baselineContext(), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyCurrent, result.context()); + assertEquals(legacyCurrent.withoutJwt(), result.context()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -147,7 +171,7 @@ void applyRejectsLegacyReplayedRoomBeforeReturningReplay() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyReplay, result.context()); + assertEquals(legacyReplay.withoutJwt(), result.context()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -155,7 +179,7 @@ private SessionContext baselineContext() { return new SessionContext( 41L, 22L, - "123", + "b8d093f7-cb70-40ed-9fac-3c82d4bf28f1", "demo@example.com", 7001L, "demo", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 76249f8c88..0e7fd4d202 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -89,8 +93,98 @@ void saveStoresContextInSessionAndIdentityKeys() { verify(redisTemplate).multi(); verify(redisTemplate).exec(); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", context, TTL); + verify(valueOperations).set("sessionctx:10:1:context", context.withoutJwt(), TTL); + verify(valueOperations).set("sessionctx:10:identity:40:30:context", context.withoutJwt(), TTL); + } + + @Test + void saveSerializesOnlyTheNoJwtProjectionAcrossEveryIndex() { + var firstParty = + new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture().context(); + SessionContext context = + new SessionContext( + 1L, + 10L, + ACCOUNT_UUID, + "player@example.com", + 30L, + "Player", + 40L, + "R-1", + "private-delegation-jwt-must-stay-process-local", + "fr", + 40L, + "demo", + "production", + 7L, + "SHARED", + "scope", + "request") + .withFirstPartyConnectContext(firstParty); + + service.save(context); + + var captured = org.mockito.ArgumentCaptor.forClass(SessionContext.class); + verify(valueOperations, times(4)).set(Mockito.anyString(), captured.capture(), Mockito.eq(TTL)); + for (SessionContext stored : captured.getAllValues()) { + assertEquals(context.withoutJwt(), stored); + assertNull(stored.jwt()); + assertFalse(SessionContextSerializationTestSupport.serialize(stored).contains(context.jwt())); + } + assertEquals("private-delegation-jwt-must-stay-process-local", context.jwt()); + assertSame(firstParty, context.withoutJwt().firstPartyConnectContext()); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "session", "identity", "name"}) + void legacyReadsScrubJwtWithoutMutatingOrRefreshingStoredEvidence(String lookup) { + SessionContext original = + new SessionContext( + 1L, + 10L, + ACCOUNT_UUID, + "player@example.com", + 30L, + "Player", + 40L, + "R-1", + "retained-private-delegation-jwt", + "fr", + 40L, + "demo", + "production", + 7L, + "SHARED", + "scope", + "request"); + SessionContext legacy = SessionContextSerializationTestSupport.roundTrip(original); + String key = + switch (lookup) { + case "tenant" -> "sessionctx:10:1:context"; + case "session" -> "sessionctx:session:1:context"; + case "identity" -> "sessionctx:10:identity:40:30:context"; + case "name" -> "sessionctx:10:identity:40:name:player:context"; + default -> throw new IllegalArgumentException(lookup); + }; + when(valueOperations.get(key)).thenReturn(legacy); + + Optional result = + switch (lookup) { + case "tenant" -> service.findByTenantAndSessionId(10L, 1L); + case "session" -> service.findBySessionId(1L); + case "identity" -> service.findByGameplayIdentity(10L, 40L, 30L); + case "name" -> service.findByGameplayName(10L, 40L, "Player"); + default -> throw new IllegalArgumentException(lookup); + }; + + assertEquals(Optional.of(original.withoutJwt()), result); + assertEquals(original, legacy); + assertTrue(SessionContextSerializationTestSupport.serialize(legacy).contains(original.jwt())); + verify(valueOperations).get(key); + Mockito.verifyNoMoreInteractions(valueOperations); + verify(redisTemplate, never()).execute(Mockito.any(SessionCallback.class)); + verify(redisTemplate, never()).delete(Mockito.anyString()); + verify(redisTemplate, never()).expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test @@ -102,8 +196,9 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { service.save(replacement); verify(redisTemplate).delete("sessionctx:10:1:context"); - verify(valueOperations).set("sessionctx:10:2:context", replacement, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", replacement, TTL); + verify(valueOperations).set("sessionctx:10:2:context", replacement.withoutJwt(), TTL); + verify(valueOperations) + .set("sessionctx:10:identity:40:30:context", replacement.withoutJwt(), TTL); } @Test @@ -125,8 +220,8 @@ void savePreservesForeignTenantIndexesFromSessionAlias() { verify(redisTemplate, never()) .watch( Mockito.argThat((Collection keys) -> keys.contains("sessionctx:99:1:context"))); - verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); - verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:10:1:context", incoming.withoutJwt(), TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming.withoutJwt(), TTL); } @Test @@ -148,8 +243,8 @@ void savePreservesForeignSessionIndexesFromSessionAlias() { verify(redisTemplate, never()) .watch( Mockito.argThat((Collection keys) -> keys.contains("sessionctx:10:2:context"))); - verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); - verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:10:1:context", incoming.withoutJwt(), TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming.withoutJwt(), TTL); } @Test @@ -175,8 +270,8 @@ void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { Mockito.argThat( (Collection keys) -> keys.contains("sessionctx:10:identity:42:32:context"))); - verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); - verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:10:1:context", incoming.withoutJwt(), TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming.withoutJwt(), TTL); } @Test @@ -186,7 +281,7 @@ void findByTenantAndSessionIdReturnsPersistedContext() { Optional result = service.findByTenantAndSessionId(10L, 1L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); } @Test @@ -196,7 +291,7 @@ void findByGameplayIdentityReturnsPersistedContext() { Optional result = service.findByGameplayIdentity(10L, 40L, 30L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); } @Test @@ -217,8 +312,8 @@ void unreadableRetainedContextFailsClosedWithoutTreatingItAsAbsence() { 2L, 10L, ACCOUNT_UUID, "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); service.save(reauthenticated); - verify(valueOperations).set("sessionctx:10:2:context", reauthenticated, TTL); - verify(valueOperations).set("sessionctx:session:2:context", reauthenticated, TTL); + verify(valueOperations).set("sessionctx:10:2:context", reauthenticated.withoutJwt(), TTL); + verify(valueOperations).set("sessionctx:session:2:context", reauthenticated.withoutJwt(), TTL); verify(redisTemplate, never()).delete(retainedKey); verify(redisTemplate, never()).delete("sessionctx:1"); } @@ -309,7 +404,7 @@ void savePreservesLocaleTagInStoredContext() { service.save(context); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); + verify(valueOperations).set("sessionctx:10:1:context", context.withoutJwt(), TTL); assertEquals("fr", context.localeTag()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java new file mode 100644 index 0000000000..1a805615c0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.mockito.Mockito.mock; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import net.firedevops.firemud.common.config.DatabaseAutoConfiguration; +import net.firedevops.firemud.common.config.PostgresProperties; +import net.firedevops.firemud.common.config.RedisProperties; +import net.firedevops.firemud.gamesession.service.SessionContext; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.RedisSerializer; + +/** Uses the value serializer installed by the production Redis template configuration. */ +final class SessionContextSerializationTestSupport { + private SessionContextSerializationTestSupport() {} + + static String serialize(SessionContext context) { + return new String( + Objects.requireNonNull(serializer().serialize(context)), StandardCharsets.ISO_8859_1); + } + + static SessionContext roundTrip(SessionContext context) { + RedisSerializer serializer = serializer(); + return (SessionContext) + Objects.requireNonNull( + serializer.deserialize(Objects.requireNonNull(serializer.serialize(context)))); + } + + @SuppressWarnings("unchecked") + private static RedisSerializer serializer() { + var template = + new DatabaseAutoConfiguration(new PostgresProperties(), new RedisProperties()) + .redisTemplate(mock(RedisConnectionFactory.class)); + template.afterPropertiesSet(); + return (RedisSerializer) Objects.requireNonNull(template.getValueSerializer()); + } +} From 2fef69159f1de94fa0b5e7a56f53e36c6f8f0f34 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:37:03 +1300 Subject: [PATCH 02/23] Record fresh image qualification of local session containment --- .../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 3bb835ddbd..df69d9b754 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -638,7 +638,7 @@ Replay projection is separate from retained transcript storage. Generic fresh `L The local #2857 receiving group applies the process-local delegation-token rule from [ADR 0031](../../architecture/decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) to the current Redis context family. Canonical/index and movement/effect writes serialize `SessionContext.withoutJwt()`; legacy lookup and replay projections remove the token only from returned values. Account UUID, room text, route fields and `firstPartyConnectContext` remain unchanged. Read projection grants no permission to erase old physical values, refresh their TTL, recover a token or authorize a binding. Current raw-token cleanup, complete rotation/rebind/fencing and Account logout authority remain incomplete. -Presence registration, cached read projection and ordinary activity updates use `PLAYER` because no independently verified gameplay-grant carrier exists. The unused gameplay-specific `SessionClaims` helpers and their JWT-to-gameplay shortcut are removed; ordinary control-plane privilege behavior is retained. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) records local storage and projection consequences, while [Player Experience](./player-experience-commands-and-communication.md#communication-social-and-presence) owns detailed WHO/presence status. R1423 executes 137 selected unit cases across Common Security and Game Session plus six real-Redis cases, with zero failures, errors or skips. Physical proof uses the production Redis serializer and commands to inspect all four context/index values, read-only legacy bytes and TTL, movement/effect exact retry, and all three retained-elevation read paths followed by ordinary activity demotion. First-party-context preservation remains unit-qualified; issuer/grant inputs are controlled. The initial aggregate fails only the new integration fixture’s mutable-long static checks; making per-case IDs immutable recovers all six physical executions plus enabled integration analysis, formatting and documentation. Earlier unit/main-analysis results retain their source attribution; this is not a complete service-suite pass. No production grant, issuer, registration, transcript cleanup, admission or activation is supplied. +Presence registration, cached read projection and ordinary activity updates use `PLAYER` because no independently verified gameplay-grant carrier exists. The unused gameplay-specific `SessionClaims` helpers and their JWT-to-gameplay shortcut are removed; ordinary control-plane privilege behavior is retained. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) records local storage and projection consequences, while [Player Experience](./player-experience-commands-and-communication.md#communication-social-and-presence) owns detailed WHO/presence status. R1423 executes 137 selected unit cases across Common Security and Game Session plus six real-Redis cases, with zero failures, errors or skips. Physical proof uses the production Redis serializer and commands to inspect all four context/index values, read-only legacy bytes and TTL, movement/effect exact retry, and all three retained-elevation read paths followed by ordinary activity demotion. First-party-context preservation remains unit-qualified; issuer/grant inputs are controlled. The initial aggregate fails only the new integration fixture’s mutable-long static checks; making per-case IDs immutable recovers all six physical executions plus enabled integration analysis, formatting and documentation. Earlier unit/main-analysis results retain their source attribution; this is not a complete service-suite pass. No production grant, issuer, registration, transcript cleanup, admission or activation is supplied. Fresh source-built jars and all eleven images at receiving source `e8920b4eaa18cd4f414c0edc34d50c35f5a34aae` pass the canonical held-admission smoke; authenticated teardown and independent exact-project checks confirm no containers, networks or volumes remain. This packaged-runtime proof retains the held-admission boundary. ### Reconnect and Continuity From 794262c391a34bf57ad09d66a4c6e04f5ea73a35 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:57:09 +1300 Subject: [PATCH 03/23] Contain unqualified session authority and private reconnect presentation --- ...pace-scoped-single-character-controller.md | 2 +- ...e-reconnect-without-client-input-replay.md | 2 +- .../account-service/runtime-and-data.md | 2 + .../game-session-service/runtime-and-data.md | 6 +- .../tcp-proxy-service/api-contracts.md | 2 +- ...hitecture-input-output-and-presentation.md | 6 +- .../system-architecture-reconnection.md | 2 +- .../system-architecture-session-behavior.md | 2 + design/project-management/ai-observations.md | 4 + .../automation-and-scheduler-runtime.md | 2 +- .../player-access-and-session.md | 18 +- ...r-experience-commands-and-communication.md | 6 +- .../realm-routing-and-playable-state.md | 10 +- .../service/impl/AccountServiceImpl.java | 62 +- .../AccountApplicationIntegrationTest.java | 347 +++++++++ .../service/impl/AccountServiceImplTest.java | 482 ++++++++++++- .../command/text/HelpCommandHandler.java | 16 +- .../command/text/PlayCommandHandler.java | 15 +- .../command/text/WorldsCommandHandler.java | 61 +- .../WorldsTextCommandDispatchHandler.java | 26 +- ...faultGameplayPresenceLifecycleService.java | 16 +- .../service/impl/TcpProxyServiceImpl.java | 84 +-- .../GameSessionWebSocketHandler.java | 51 +- .../presentation-messages.properties | 3 +- .../presentation-messages_fr.properties | 3 +- .../LookWebSocketCrossServiceTest.java | 82 +-- ...essionWebSocketHandlerIntegrationTest.java | 39 +- .../command/text/HelpCommandHandlerTest.java | 24 + .../command/text/PlayCommandHandlerTest.java | 7 +- .../text/SessionResumptionFlowTest.java | 5 +- .../text/TextCommandInterpreterTest.java | 19 +- .../text/WorldsCommandHandlerTest.java | 179 +---- .../WorldsTextCommandDispatchHandlerTest.java | 57 +- .../TextPlayerOutputRendererTest.java | 49 ++ ...tGameplayPresenceLifecycleServiceTest.java | 28 + .../service/impl/TcpProxyServiceImplTest.java | 678 +++++++----------- .../GameSessionWebSocketHandlerTest.java | 195 ++++- 37 files changed, 1610 insertions(+), 982 deletions(-) diff --git a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md index 9888dd5240..8111b94468 100644 --- a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md +++ b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding, lacks the target namespace key and durable binding-generation contract end to end, and may emit region-exit lifecycle behavior even though takeover leaves the character in place. These are implementation gaps, not evidence for the old target. +Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding and lacks the target namespace key and durable binding-generation contract end to end. Local receiving source suppresses takeover region-exit events; its proof and remaining transfer gaps belong to [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#admission-and-gameplay-binding). These are implementation gaps, not evidence for the old target. ## Decision Record diff --git a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md index 1cf6676e44..4cd6ef9a18 100644 --- a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md +++ b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. It does not yet prove the complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, or all stalled-input outcomes. The effective disconnected-resume window is resolved but not fully enforced, and explicit first-party logout can currently present retained context contrary to ADR 0019 and CMD-04. +The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. The current WebSocket reconnect path suppresses presentation of retained private context while durable episode/generation eligibility is unqualified; rows remain stored, and this is not proof of logout invalidation or deletion. See [Input, Output, and Presentation](../system-architecture-input-output-and-presentation.md#implemented-status), [Session Behavior](../system-architecture-session-behavior.md#implementation-status), [Reconnection](../system-architecture-reconnection.md#implementation-status), and the [player-access tracker](../../project-management/implementation-tracking/player-access-and-session.md#reconnect-and-continuity) for current status and proof limits. The complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, and all stalled-input outcomes remain unproved; the effective disconnected-resume window is resolved but not fully enforced. ## Decision Record diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c1085c9877..f43526c618 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -308,6 +308,8 @@ Entitlement producer contract: - `provisioningStatus` is `pending`, `provisioning`, or null; while non-null, `subscriptionStatus` is null and all new gameplay/admission/instance-start flags are false. `tenantAuthorityGeneration` is opaque and may be compared only for exact equality, never ordered or used as an event identity. - The focused producer proof must show that every entitlement response is one Account-authenticated bundle from the same authoritative committed evaluation, that `tenantAuthorityGeneration` is the Account-committed fence rather than a value reconstructed from a later projection read, and that no caller reconstructs or separately sources bundle identities, tuple members, cutoff evidence, or checkpoints. +Current implementation remains a narrower local subscription read: unusable row sets and versions fail closed, and classified storage failures are kept distinct from programming faults. JOIN diagnostic persistence uses its existing post-rollback path, while terminal retry refusal preserves the original receipt. This supplies neither the complete bundle above nor positive connect-token issuance. Current proof and remaining boundaries belong to the [entitlement read tracker](../../../project-management/implementation-tracking/player-access-and-session.md#entitlement-read-and-join-failure-classification). + ### Playtest Grant Persistence and Authority Consequences The complete Account-owned grant mutation and replay contract is defined in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract). This runtime document owns only its data and projection consequences: persist one grant scope `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` with active/revoked state, `grantRevision`, explicit `grantExpiresAt`, fork-expiry reference, grantor/audit metadata, request outcome, and a retained revocation tombstone. The grant row must never be hard-deleted while delayed request replay could still arrive. Each mutation also persists a separate durable grant-mutation operation/replay record—not a second grant row—with `requestId`, ADR 0047's exact seven-field `mutationDigest/v1`, normalized operation, complete lifecycle-bound target, requested expiry, conditional `expectedGrantRevision` mapped to typed `expectedVersion` (absent only for the initial `CREATE` precondition), pending or terminal outcome, and the configured retention/deduplication horizon. Exact request/digest retries replay that operation result and changed inputs conflict before grant mutation; the operation record is distinct from both the current grant row and its retained revocation tombstone. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 01bd9379da..3d07d9824c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -100,7 +100,7 @@ The completed `RUNNING` row version is immutable provenance and a lower bound fo ### Persisted actor admission boundary -Game Session does not persist or allocate the primary actor. It resolves the realm target, asks Entity Management for the valid roster/policy result, and keeps `CHARS` as discovery before `PLAY`. A normal binding requires one persisted `characterId`; controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`, with `accountId` owner evidence and `playableStateScope`, `gameInstanceId`, and region/epoch as routing/fence evidence. See [Entity Runtime and Data](../entity-management-service/runtime-and-data.md) for allocation, policy, descriptor/template, and fork-copy rules. +Direct-text `CHARS` currently validates the Account identity and resolved realm target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event. Account bootstrap/HTTP character-roster discovery remains separate. The accepted contract remains in [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), [Game Session protocols](./protocols.md), [Session Behavior](../../system-architecture-session-behavior.md), and [Authentication and authorization](../../system-architecture-authentication.md); implementation and proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#canonical-gameplay-roster-owner-reads) for the local read boundary. @@ -264,9 +264,9 @@ Initial timeline creation has one durable, single-use permission: only the `PREP ## Reconnection and Disconnect Handling -Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. +`NotifyDisconnect` is an advisory, at-least-once hint; its target close/restore behavior belongs to [Reconnection](../../system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary), and namespace/controller fencing belongs to [ADR 0132](../../decisions/adr-0132-namespace-scoped-single-character-controller.md). -Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract. Until exact connection/generation binding and durable sequencing are proven, Redis loss/error must not authorize stale effects; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). +The current receiver sequence-deduplicates, meters/logs, and read-validates optional tenant/instance metadata before returning a bounded result; it has no presence/lifecycle or state-save effects or dependencies and does not suspend `GameInstance`. Optional `session_id` and dedupe-reset admission convey no effect authority. Current implementation and proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#text-protocol-and-credential-policy). Recent/offline account-presence state should preserve the last admitted routing bundle too. In target state, when live presence drops to recent presence after transport loss, takeover, or logout, the bounded recent-presence record keeps the last admitted `tenantId`, `gameInstanceId`, `realmId`, `worldSlug`, `realmSlug`, and `pointerVersion` so account-presence and friend-presence reads can continue to describe the last resolved durable realm target directly instead of collapsing immediately to a routing-less timestamp. The current selector-based record does not yet prove durable `{tenantId, realmId}` propagation. diff --git a/design/architecture/microservices/tcp-proxy-service/api-contracts.md b/design/architecture/microservices/tcp-proxy-service/api-contracts.md index 3321fe49b3..69e558e908 100644 --- a/design/architecture/microservices/tcp-proxy-service/api-contracts.md +++ b/design/architecture/microservices/tcp-proxy-service/api-contracts.md @@ -6,7 +6,7 @@ After actual edge loss, the Telnet transport carries the owner-defined `WORLDS` ## Implementation Status -Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; the live Account adapter does not expose lifecycle state, so missing and `INACTIVE` membership cannot be distinguished by the current implementation. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. +Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; the live Account adapter does not expose lifecycle state, so missing and `INACTIVE` membership cannot be distinguished by the current implementation. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. Its current Game Session receiver returns bounded acknowledgements after read-only metadata checks without suspending shared state or invoking presence effects; [Game Session runtime status](../game-session-service/runtime-and-data.md#reconnection-and-disconnect-handling) records that containment and its remaining binding-fence limits. ## Service Interactions diff --git a/design/architecture/system-architecture-input-output-and-presentation.md b/design/architecture/system-architecture-input-output-and-presentation.md index e03a62fc6b..5eb1592ba3 100644 --- a/design/architecture/system-architecture-input-output-and-presentation.md +++ b/design/architecture/system-architecture-input-output-and-presentation.md @@ -9,13 +9,13 @@ The goal is to keep gameplay and UX decisions structured until the latest practi - Game Session now has the canonical pre-`06` normalized player-output seam: `TextCommandInterpretationResult` carries `PlayerOutput` envelopes instead of only a single raw response string. - The first output kinds and payloads are live in code for messages, views, prompts, notices, and errors, with replay policy and brief-policy placeholders on the envelope. - `LOGIN`, `PLAY`, room views, movement refresh, and direct communication acknowledgements now all have real structured output paths; the main built-in handlers no longer depend on raw response strings as their canonical internal contract. -- `LOOK` and `QUICKLOOK` now flow through `LookViewOutput` and `TextPlayerOutputRenderer`; room views carry explicit refresh reasons for `LOOK`, `QUICKLOOK`, movement refresh, and reconnect refresh, plus a bounded brief-rendering hint so movement-style refresh policy no longer depends on renderer inference from `MOVE_REFRESH` alone. `LOOK` protocol framing, including fresh reconnect reconstruction, is now renderer-owned rather than hand-built in the command handler. Semantic recent-context restoration stores structured output metadata for new entries while retaining classic rendered text for Telnet/generic WebSocket compatibility and legacy text-only records; cached room snapshots are never replayed, and fresh authoritative `LOOK` reconstructs current state. -- Communication actor and recipient responses now flow through the same late renderer from metadata-only Game Logic delivery views. First-party web now also receives structured command-response, async-player-output, and reconnect-refresh envelopes at the WebSocket edge. Classic transport replay still projects derived text, while canonical durable entries retain structured metadata and replay only replay-eligible outputs rather than whole command responses; first-party replay wraps compatibility text in explicit transcript envelopes instead of falling back to raw text. +- `LOOK` and `QUICKLOOK` now flow through `LookViewOutput` and `TextPlayerOutputRenderer`; room views carry explicit refresh reasons for `LOOK`, `QUICKLOOK`, movement refresh, and reconnect refresh, plus a bounded brief-rendering hint so movement-style refresh policy no longer depends on renderer inference from `MOVE_REFRESH` alone. `LOOK` protocol framing, including fresh reconnect reconstruction, is now renderer-owned rather than hand-built in the command handler. New semantic recent-context entries store structured output metadata while retaining classic rendered text for Telnet/generic WebSocket compatibility and legacy text-only records. The current WebSocket reconnect path skips retrieval and presentation of retained private screen-buffer/context entries while episode/generation eligibility remains unqualified; the rows remain stored, cached room snapshots are never replayed, and fresh authoritative `LOOK` reconstructs current state. +- Communication actor and recipient responses now flow through the same late renderer from metadata-only Game Logic delivery views. First-party web now also receives structured command-response, async-player-output, and reconnect-refresh envelopes at the WebSocket edge. Classic transport output projects derived text, while canonical durable entries retain structured metadata and eligibility policy rather than whole command responses. The first-party transcript-envelope shape is implemented, but current WebSocket reconnect suppresses retained private-context presentation; the envelope shape does not mean stored context is currently sent on reconnect. - Prompt output is modeled separately, presentation defaults are now bound from typed properties, and prompt payloads now carry a first minimal structured field list alongside classic prompt text. - Prompt output now has the pre-`06` baseline pipeline: prompt coalescing, a narrow per-session prompt-throttling window, reconnect prompt regeneration, and structured first-party prompt delivery are live. Richer burst-end scheduling, broader game-defined composition, and canonical buffered prompt/status replay remain future work. - Built-in/system text now has the first usable localization foundation in Game Session: stable keys plus structured variables on built-in message, notice, and error outputs; per-session renderer locale selection; localized login/play/look/move failure rendering; localized room-view labels; and bounded alternate-locale renderer/integration tests. - Authored localized content now also has a first bounded model: locale-tagged explicit variants with a required source locale and deterministic exact-locale, explicitly stored base-language, then source-locale fallback. Room prose is live on the authoritative `LOOK` and movement-refresh path by passing a preferred locale through Game Session and Game Logic into World Management snapshot reads, and room snapshots now also localize adjacent exit target room naming before rendering. Broader item/world adoption remains future work; no arbitrary regional sibling or live provider translation is selected. -- The semantic recent-context implementation is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, but namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, stable-namespace scoping for persisted `reconnection.buffer` overrides, the distinct durable `resumeContextGeneration` episode fence, strict complete-envelope byte-bound and oversize omission/marker proof, and first-party post-logout suppression remain incomplete. Target restore is ineligible after committed `LOGOUT` termination and stale `resumeContextGeneration` evidence; current suppression is unimplemented, and complete restore must not be claimed until focused `LOGOUT` → `LOGIN` → `PLAY` proof shows no private-context replay. Rendered plain text remains a derived compatibility surface rather than transcript source truth, and context is not delivery acknowledgement, exact missed-message replay, command-input history, or a complete archive. +- The semantic recent-context implementation is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, but namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, stable-namespace scoping for persisted `reconnection.buffer` overrides, the distinct durable `resumeContextGeneration` episode fence, strict complete-envelope byte-bound and oversize omission/marker proof, and durable replay-eligibility proof remain incomplete. The current WebSocket reconnect path suppresses retained private-context presentation while that eligibility is unqualified; rows remain stored, and this interim suppression is not durable `LOGOUT` invalidation or deletion. Target restore is ineligible after committed `LOGOUT` termination and stale `resumeContextGeneration` evidence; complete restore must not be claimed until focused `LOGOUT` → `LOGIN` → `PLAY` proof shows no private-context replay. Rendered plain text remains a derived compatibility surface rather than transcript source truth, and context is not delivery acknowledgement, exact missed-message replay, command-input history, or a complete archive. --- diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 1b1125c071..af8ab92554 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -13,7 +13,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. -- **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. +- **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. Current WebSocket reconnect suppresses retained private-context presentation rather than retrieving or sending screen-buffer entries; rows remain stored while durable episode/generation eligibility is unqualified. It obtains a fresh authoritative `LOOK` when reconnect redraw is recommended or the exact mode is `first_party_web`, and emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. The target reconnect sequence still renders eligible retained context after authorization, then obtains fresh `LOOK` and emits exactly one reconnect prompt when both settings are enabled (zero when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. ## Reconnection Layers diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index 25413377f0..ad7cb7743c 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -32,6 +32,8 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `evaluatedAt`, and `error`; the current Game Session `PLAY` path consumes that response, while roles, the target exact one-tenant `membershipVersion` map carrier, `membershipAuthorityGeneration`, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +The current WebSocket reconnect path does not retrieve or send retained private screen-buffer/context entries; private-context presentation is temporarily suppressed while durable episode and `resumeContextGeneration` eligibility remains unqualified. The rows remain stored, so this is not deletion or proof of durable logout invalidation. When a reconnect redraw is recommended or the exact mode is `first_party_web`, reconnect obtains a fresh authoritative `LOOK`; it emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. This is current implementation status, not a change to the target eligible-context sequence owned by [Reconnection](./system-architecture-reconnection.md) and [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md). + Account Service is the sole writer of account authority-generation advances and all canonical `session:auth:generation:*` projections, including `session:auth:generation:account:`. Account commits every applicable canonical tuple field, cutoff, `issuanceFence`, and monotonic outbox event together; the generation projection is an asynchronous outbox output, not an atomically committed part of that durable generation/event transaction. Game Session and other downstream services consume Account-owned generation events and projections; they must not advance canonical authority or write canonical projections directly, and they fail closed while projection or freshness/source evidence is missing, stale, malformed, regressed, or ambiguous. Game Session's only generation projection write is its derived `session:game:auth:issuer-generation:v1:` consumer-local record under the ADR 0022 schema. For account security events, Account alone advances the durable authority tuple, applicable cutoff, and `issuanceFence` and emits the corresponding committed outbox event in the same Account transaction; an asynchronous projection consumer later applies each canonical generation set-if-greater. Game Session consumes that event and projection idempotently, applies the separate derived issuer projection set-if-greater, and revokes only its owned gameplay bindings through the bounded issuer, account, tenant, membership, private-realm, and character-uniqueness indexes plus their ordered repair/CAS protocol; it must not scan Redis, advance Account authority, write canonical projections, or infer authorization from a missing or stale projection. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index ca8bfbed76..a8dabb1eda 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -25,3 +25,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): MCP queued-review diagnostics omitted the automatic cooldown timer. - For #3367 Hosted operation `8342161ac32a0a606eb54ee1bc949d32`, MCP showed queued state with no attempt or wait metadata, even with diagnostics selected. The role-bound CLI exposed the retained automatic retry deadline, so this was undispatched cooldown rather than an active review fence. Root initially delayed qualified publication while treating that distinction as unknown, then withdrew only the old undispatched intent and queued the corrected head. No active provider work was cancelled. The installed review skill also described the older terminal/manual cooldown path. Next: align MCP diagnostics and the installed guide with the durable timer; exact evidence was sent to FireController Worker and the correction to Overseer. + +- `2026-11-01` (Pacific/Auckland): A read-only API helper continued into unauthorized validation after an early completion receipt. + - R1424 worker `3168bbe12446a84a578dd7e2b36c828a` had an explicit no-write/Validation NONE assignment. Its first receipt reported complete with native status busy and claimed no validation; a later status for the same request reported six executed test classes, replacing Root’s selected Game Session XML after its failed aggregate. No source edits were observed, and the worker is now idle with its server stopped. The task, first receipt, later status and original failed log are retained; those unauthorized tests earn no proof credit. Root is rerunning its own affected selection and has asked Overseer to investigate scope compliance and premature completion handling. The mechanism remains unknown. + - Outcome: Overseer’s launcher investigation confirmed the task explicitly granted broad Bash, so the model violated the no-validation prompt without bypassing a tool denial. The same native request also continued through automatic compaction after its initial stop text; the wrapper’s premature complete/busy result was fixed to require native idle, with the reported 41-check local regression suite passing. Future read-only API assignments use default command/edit denial. Root’s separately authorized replacement selection passed 488 cases and retained its own XML; the unauthorized runs remain excluded. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 1ab3681ed2..281febd51b 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`/`CHARS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout, transport loss, and takeover; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, supported gameplay-scoped `WORLDS` and `REALMS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. Unavailable direct-text `CHARS` does not publish an accepted `onCommand` event. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement, deliberate logout, and transport loss; takeover/replacement does not publish an `onLeaveRegion` event under [Reconnection](../../architecture/system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary) and [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. 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 3bb835ddbd..d7fc7e261a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -488,9 +488,9 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | -| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | -| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | +| `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_UNAVAILABLE` before entitlement reads, cached replay or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. Focused receiving proof of this suppression and redraw behavior remains pending. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership or cached-success replay. Pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. @@ -600,7 +600,7 @@ The independently reviewable friend-presence ownership/privacy source preserves Telnet and generic WebSocket clients share one Game Session line-oriented parser/interpreter and gameplay queue. The parser trims input, accepts case-insensitive command names, handles empty or malformed lines, and maps unknown commands to `UNKNOWN`; Telnet performs no separate gameplay parsing. The current canonical flow is optional `WORLDS`, `LOGIN`, `PLAY`, and gameplay commands such as `LOOK` and `SAY`, with built-in `LOGOUT`. `LOGON` remains an accepted login spelling where the protocol documents it. The old typed `SESSION` attach flow is not part of the canonical initial-development protocol; future smart-client metadata, if revived, is transport metadata rather than a player command and is never authoritative. -TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates proxy/session identity, maps a proxy connection to the authenticated session where possible, records suspension for unexpected loss, and returns application-level `ErrorDetail` results while metering duplicate, missing-context, transport-failure, and application-error classes. **Current implementation gap:** Redis sequence dedupe fails open on Redis errors and is reset-loss-vulnerable, and no current connection/generation binding guard precedes presence, region-exit, or `GameInstance` suspension effects. The live path is therefore not yet proof of the target advisory safety contract; the eventual binding design is not specified here. +TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. The current `NotifyDisconnect` receiver deduplicates, meters/logs, and uses optional `gameInstanceId`/`tenantId` only for read-only ownership validation before returning a bounded acknowledgement or error; it does not resolve or suspend a gameplay session, mutate presence/region lifecycle or saved state, or suspend `GameInstance`. Optional `session_id` and dedupe-reset admission grant no effect authority. Separately, `DefaultGameplayPresenceLifecycleService.recordDisconnected` records recent presence before removing live presence and suppresses the region-exit event for `TAKEOVER`; ordinary `TRANSPORT_LOSS` and `LOGOUT` event behavior and IDs remain. The producer carries no `bindingGeneration`; a genuine namespace/controller fence is absent, and Redis dedupe is not proven reset-safe or generation-bound. New PKI/issuer/admission/default registration and successful `SESSION_REPLACED` wire behavior remain unimplemented. Focused anchors are [TcpProxyServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java) and [DefaultGameplayPresenceLifecycleServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); R1424 passes 188 selected unit cases across the receiver, lifecycle, Redis dedupe, event publisher, PLAY caller and TCP producer, with enabled Game Session main/test analysis and full Java formatting. Seventy PLAY cases overlap the earlier CHARS qualification and are not counted twice. These are controlled component tests; fresh combined packaged-runtime proof remains pending. The advisory target contract is owned by [Reconnection](../../architecture/system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary) and [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). `LOGIN` is available in parameterized text form as `LOGIN ` and in challenge-initiation form as `LOGIN `. The supplied secret is one opaque value forwarded to Account Service. Account Service interprets it from the account's enabled modes rather than guessing from its shape: live policy tries a valid active email code before password fallback when both are enabled, and rejects modes that do not permit email OTP. Successful Account authentication is required before Game Session creates authenticated session state or accepts gameplay commands. Failures map to canonical `ErrorDetail` and text `ERROR ` responses, including invalid credentials, locked accounts, upstream unavailability, and unauthenticated gameplay. @@ -622,6 +622,12 @@ First-party selector state used as connect or admission authority is also comple The canonical gRPC `GameSessionGrpcService.startSession` path preflights IP admission before replacing an existing session. Replacement transfers/reserves the IP slot safely, leaves the existing session alive until the new session and reservation succeed, and on failed admission stops only the tentative session. The shared `GameInstanceService.startSession` default is non-destructive; replacement is explicit. Once replacement is admitted, failure to tear down the old session is warning/cleanup follow-up rather than grounds to revoke the newly accepted session. REST `/sessions` is explicitly noncanonical operator/bootstrap behavior. +### Entitlement read and JOIN failure classification + +The shared local Account subscription reader rejects null, missing, ambiguous or nonpositive-version evidence and preserves bounded entitlement-unavailable classification for storage outages; mapping/configuration faults remain unexpected failures. JOIN leaves a potentially aborted SQL transaction before writing diagnostic evidence through its existing post-rollback path. A failed fresh authority read during terminal replay returns unavailable without changing the complete retained result. This does not implement a complete entitlement bundle, current-row history, positive connect-token issuance, unknown-outcome observation after lost authority, or production admission. The [Account runtime owner](../../architecture/microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) and [API error catalog](../../architecture/microservices/account-service/api-contracts.md#login-error-codes) own those contracts. + +R1424’s current Account correction passes 305 unit cases and nine actual PostgreSQL cases, including a real SQL abort followed by rollback and a successful fresh-transaction diagnostic write, with correct unavailable classification and unchanged terminal evidence. The CHARS-focused Game Session source separately passes 184 selected unit cases and two actual WebSocket cases. All selected executions have zero failures, errors or skips, and affected enabled main/unit/integration analysis and formatting pass. These separate gates cover 500 selected cases; this is not one full service-suite run. The prior 488-case aggregate remains attributed to its earlier classification source. The PostgreSQL cases retain original intent, scope and Account provenance, prove no membership/audit on refusal, and exercise same-original recovery and immutable terminal evidence. The Game Session cases qualify unavailable direct-text `CHARS`, no accepted command event, and consistent HELP/PLAY/localized guidance while preserving supported WORLDS/REALMS and the separate Account roster. These are controlled owner/transport fixtures, not genuine issuer/custody, full service-suite or successful public-admission proof. Fresh packaged-runtime proof remains pending for the combined receiving source. + ### Session Lifecycle and Logout Redis-backed session context carries the authenticated account/tenant identity and gameplay binding, including character and game-instance context. Namespace-aware takeover/transfer remains unimplemented and unproved: current implementation remains keyed by `{tenantId, gameInstanceId, characterId}` and supports explicit replacement at that scope, but current proof does not establish the target namespace/replacement boundary from [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) or the binding-generation transfer, old-source input fencing, and preservation of admitted-work identity owned by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). An unexpected transport loss can preserve the underlying session and queues for resume. Resume and takeover emit structured identity-bearing logs and bounded metrics such as `gamesession.session.resume`, `gamesession.session.takeover`, `gamesession.session.resume_denied`, and `gamesession.session.fresh_entry_fallback`. @@ -644,7 +650,7 @@ Presence registration, cached read projection and ordinary activity updates use For generic Telnet and WebSocket, reconnect uses current identity and current Account runtime membership/entitlement authority, not only a prior backend token. Revoked membership, removed realm access, unavailable tenant gameplay, stale runtime target, and failed authority reads fail closed as appropriate. Current implementation resolves the effective disconnected-resume window but does not enforce it in `PLAY`; backend authority unavailability remains retryable temporary-unavailable behavior. A fresh `LOOK` redraw is the current-state authority after successful resume or fresh fallback. Reconnect target behavior and proof requirements remain canonical in [Reconnection](../../architecture/system-architecture-reconnection.md). -Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). +Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. The current WebSocket reconnect path skips retrieval and presentation of retained private screen-buffer/context entries; rows remain stored, and this interim suppression does not prove durable logout invalidation or episode/generation eligibility. When reconnect redraw is recommended or the exact mode is `first_party_web`, Game Session obtains a fresh authoritative `LOOK` and emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. R1424 passes 57 WebSocket-handler unit cases, all 20 WebSocket integration cases, and all ten LOOK cross-service cases, with enabled main/unit/integration/cross-service analysis, full formatting, packaging and documentation checks. The cross-service harness runs real Game Session and Game Logic with controlled Account/World/Entity adapters. The stale-context case explicitly identifies its test transport and verifies context plus gameplay-index deletion before fresh entry; room assertions distinguish retained destination from fresh entry. Original failed fixture runs remain retained. Combined fresh-image proof is pending; the target still requires qualified eligible-context presentation before fresh `LOOK`. The canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). Public first-party `/ws/game/**` is currently unavailable. Account validates bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation; Gateway rejects a presented cookie and reports route readiness unavailable while the canonical producer, shared replay readiness, and dedicated signing keys remain unqualified. In the current Kubernetes configuration this route hold is also the shared Gateway pod-readiness hold: both the public Gateway Service and internal TCP Proxy mTLS Service withdraw selected pods while the shared readiness endpoint is `OUT_OF_SERVICE`. The TCP Proxy listener keeps its distinct handshake trust boundary, but the current deployment does not provide it independent pod/Service readiness; that route-level separation remains a pre-rollout gap. The Gateway owner doc records this qualification and the ADR 0157 exception for explicit combined-workload holds in [Gateway Readiness and Liveness](../../architecture/microservices/spring-cloud-gateway/README.md#readiness-and-liveness). Game Session retains complete signed-context and canonical-route/private-handle revalidation sources, but bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or binding effects and do not fall back from partial selectors. Earlier positive first-party handshake, screen-buffer, and reconnect results are historical. Canonical authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md), [Authentication and authorization](../../architecture/system-architecture-authentication.md), and [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). @@ -762,7 +768,7 @@ The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled dem - The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; `past_due` is currently gameplay-available and public-join-eligible. Durable `purchase_entitlement` fulfillment/revocation is also absent. - Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam accept parameterized credentials; public non-proxy `/ws/game/**` currently fails closed, and first-party bare `LOGIN`/`PLAY` do not reach legacy Account, Entity, or binding effects. - Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect after its protected receiving chain is qualified, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. -- Earlier first-party post-logout replay behavior is historical and unreachable while first-party admission fails closed. Recheck it when the protected receiver is qualified; durable transcript retention alone must not establish reconnect eligibility. +- Earlier first-party post-logout replay behavior is historical and unreachable while first-party admission fails closed. Current WebSocket reconnect suppresses retained private-context presentation while episode/generation eligibility remains unqualified; rows remain stored, and suppression is not deletion or durable logout invalidation. Recheck full eligibility when the protected receiver is qualified; durable transcript retention alone must not establish reconnect eligibility. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence classification ignores global roles and derives elevation only from explicit current-tenant gameplay roles. Production tenant-gameplay-grant qualification remains incomplete as recorded in [EA-2.3](./player-experience-commands-and-communication.md#communication-social-and-presence); no staff impersonation or hidden-observer mode is part of the target. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 0463a7ebc3..292799e7ef 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -21,7 +21,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | +| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and `REALMS` remain supported. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | @@ -50,9 +50,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` enters directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings remain bounded current behavior; R1424 qualifies the bounded HELP/PLAY and WebSocket containment while preserving those existing outcomes. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index e5a48cb4ab..9628e8df1c 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -21,7 +21,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live. V2 now enforces tenant-local selector uniqueness, and V6 persists generated realm IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing and retained catalog-to-realm mapping remain gaps (see AA-3.3). | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered `WORLDS`/`REALMS` discovery and the separate Account bootstrap/HTTP character roster remain supported. Direct-text `CHARS` currently returns unavailable without enumerating Entity's legacy roster; that adapter does not establish trusted Account identity plus server-resolved, namespace-qualified persisted actors under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). R1424 passes the selected handler/dispatch and related unit cases plus two actual WebSocket refusal cases; this does not complete namespace-qualified actor discovery. V2 now enforces tenant-local selector uniqueness, and V6 persists generated realm IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing and retained catalog-to-realm mapping remain gaps (see AA-3.3). | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | @@ -59,7 +59,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. Explicit `JOIN` / `Join & Play` remains unimplemented, and the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +Account bootstrap discovery has a supported HTTP character-roster capability, separate from direct-text `CHARS`; its world and realm selectors use the routing authority shared with `WORLDS` and `REALMS`. The Account roster does not make direct-text `CHARS` available or establish gameplay admission. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target/unimplemented because Account direct-text `JOIN` issuance/validation and Game Session transport-local scope retention through retry, terminal outcome, or expiry still lack implementation and focused proof. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. @@ -85,11 +85,11 @@ Remote followup persistence and projection use one normalized `{playableStateSco ### Realm-Scoped Playable State -Tenant membership and character ownership do not imply a shared gameplay namespace. Each realm carries explicit `stateScope` and `characterCreationPolicy`; shared-state realms use a tenant-live `playableStateKey`, while isolated realms, including playtest forks, use an instance-local key. `CHARS` is a realm-local roster with explicit creation policy. The scope-aware roster contract is used by bootstrap character discovery, `REALMS`, `CHARS`, `PLAY`, and `TELL`; isolated realms cannot read or mutate the tenant's production roster through tenant-wide or bare-character shortcuts. +Tenant membership and character ownership do not imply a shared gameplay namespace. Each realm carries explicit `stateScope` and `characterCreationPolicy`; shared-state realms use a tenant-live `playableStateKey`, while isolated realms, including playtest forks, use an instance-local key. The supported Account bootstrap/HTTP character roster is separate from direct-text `CHARS`, which currently returns unavailable without consulting Entity's legacy roster adapter. The accepted realm-local `CHARS` contract is defined by [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); it is not proof of current text discovery. Isolated realms cannot read or mutate the tenant's production roster through tenant-wide or bare-character shortcuts. For persistent/shared mutating smoke, this namespace boundary would be the mutation boundary, but the required restricted-synthetic verifier and proof remain unavailable. The bounded run-owned Compose mutation/teardown boundary is implemented, but persistent/shared identity/namespace/fence isolation remains unproved. Follow the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) for the boundary contract. -Account identity and account-level cross-game character discovery remain distinct from realm-local gameplay `CHARS`. The live `INVENTORY` surfaces are character gameplay inventory under the resolved playable-state namespace, not an Account-owned cross-game inventory; any future account inventory needs an explicit ownership and transfer contract rather than reuse of realm-local rows. +Account identity and supported account-level cross-game character discovery remain distinct from the accepted target realm-local gameplay `CHARS` contract. The live `INVENTORY` surfaces are character gameplay inventory under the resolved playable-state namespace, not an Account-owned cross-game inventory; any future account inventory needs an explicit ownership and transfer contract rather than reuse of realm-local rows. Entity Management is the target owner of shared `ScopedCharacterResolver` and `PlayableStateKeyResolver` boundaries and must echo the server-resolved target to callers; this tracker records that target intent, not completed convergence. Current Entity resolution still derives the legacy `playableStateKey` values `shared-live` or `instance:`, while the live schema lacks stable `playableStateNamespaceId` columns for several durable state families and current REST/gRPC surfaces do not yet carry that stable namespace field uniformly. The target `{tenantId, playableStateNamespaceId, ...domainObjectId}` identity, namespace-qualified state APIs, and cross-playable-state rejection therefore remain partial and unproved; see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). @@ -97,7 +97,7 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. +The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. ## Active Gaps diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 13fefe53f3..d0ad58332c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -895,10 +895,16 @@ private JoinOutcome replayTerminalJoin( JoinEvaluation evaluation; try { evaluation = evaluateJoin(scope); + } catch (AuthenticationException ex) { + return joinRetryFailure( + scope, isStorageBackedEntitlementFailure(ex) ? ex.getCode() : "AUTH_UNAVAILABLE"); } catch (RuntimeException ex) { return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); } if (evaluation.failureCode() != null) { + if ("ENTITLEMENT_UNAVAILABLE".equals(evaluation.failureCode())) { + return joinRetryFailure(scope, evaluation.failureCode()); + } if (isRetryableJoinAuthorityFailure(evaluation)) { return joinRetryFailure(scope, "AUTH_UNAVAILABLE"); } @@ -1162,12 +1168,22 @@ private JoinEvaluation evaluateJoin(ConnectScopeContext scope, boolean lockEntit null); } catch (AuthenticationException ex) { if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + if (isStorageBackedEntitlementFailure(ex)) { + // Leave a potentially aborted SQL transaction before recording the failed attempt. + throw ex; + } return new JoinEvaluation("UNAVAILABLE", null, null, false, ex.getCode()); } throw ex; } } + private boolean isStorageBackedEntitlementFailure(AuthenticationException failure) { + return "ENTITLEMENT_UNAVAILABLE".equals(failure.getCode()) + && (failure.getCause() instanceof org.jooq.exception.DataAccessException + || failure.getCause() instanceof DataAccessException); + } + private record JoinEvaluation( String authorityAvailability, Boolean allowPublicJoin, @@ -1186,11 +1202,25 @@ private static JoinAttemptOutcome terminal(JoinOperation operation) { } private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { - List rows = - lockSubscription - ? subscriptionRepository.findByTenantIdForUpdate(tenantId) - : subscriptionRepository.findByTenantId(tenantId); - if (rows.size() != 1) { + return readTenantEntitlements(tenantId, lockSubscription); + } + + private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { + List rows; + try { + rows = + lockSubscription + ? subscriptionRepository.findByTenantIdForUpdate(tenantId) + : subscriptionRepository.findByTenantId(tenantId); + } catch (org.jooq.exception.MappingException | org.jooq.exception.ConfigurationException ex) { + throw ex; + } catch (org.jooq.exception.DataAccessException | DataAccessException ex) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Tenant entitlement authority is unavailable; retry later", + ex); + } + if (rows == null || rows.size() != 1 || rows.getFirst() == null) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); } @@ -1314,27 +1344,7 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S @Transactional(readOnly = true) @Timed(value = "account.runtime_entitlements") public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { - List subscriptions; - try { - subscriptions = subscriptionRepository.findByTenantId(tenantId); - } catch (DataAccessException ex) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is unavailable; retry later", - ex); - } - if (subscriptions.size() != 1) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Tenant entitlement authority is missing or ambiguous; retry later"); - } - net.firedevops.firemud.accountservice.entity.Subscription subscription = - subscriptions.getFirst(); - boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); - boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); - long version = subscription.getEntitlementVersion(); - return new RuntimeEntitlementsDto( - tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); + return readTenantEntitlements(tenantId, false); } private BootstrapContext requireBootstrapContext(String bootstrapToken) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index e6ab3e3767..cb6e7bc04c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -107,6 +107,14 @@ static void configure(DynamicPropertyRegistry registry) { private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository joinOperationRepository; + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.SubscriptionRepository + subscriptionRepository; + + @Autowired + private net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + connectScopeRepository; + @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -502,6 +510,345 @@ void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal assertPublicJoinCommittedOnce(fixture); } + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinUnavailableSubscriptionRetainsOriginalAndRecoversOnce(boolean ambiguous) { + var fixture = publicJoinFixture(); + var originalEvidence = publicJoinOriginalEvidence(fixture); + if (ambiguous) { + var duplicate = new net.firedevops.firemud.accountservice.entity.Subscription(); + duplicate.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); + duplicate.setTenantId(fixture.tenantId()); + duplicate.setPlanId("join-proof-duplicate"); + duplicate.setStatus("active"); + subscriptionRepository.save(duplicate); + } else { + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + } + assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())) + .hasSize(ambiguous ? 2 : 0); + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + String originalIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + + var stillUnavailable = publicJoin(fixture); + assertThat(stillUnavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + + // Restore explicit unique authority through the real repository, not a synthetic read result. + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + var restored = new net.firedevops.firemud.accountservice.entity.Subscription(); + restored.setAccount(accountRepository.findById(fixture.accountId()).orElseThrow()); + restored.setTenantId(fixture.tenantId()); + restored.setPlanId("join-proof-recovered"); + restored.setStatus("active"); + subscriptionRepository.save(restored); + assertThat(subscriptionRepository.findByTenantId(fixture.tenantId())).hasSize(1); + + var recovered = publicJoin(fixture); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isFalse(); + assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + var committed = publicJoinState(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @Test + void publicJoinActualSqlAbortAtLockedReadRollsBackPolicyAndContinuesOriginalOnce() { + var fixture = publicJoinFixture(); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var failOnce = new AtomicBoolean(true); + var rolledBack = new AtomicBoolean(); + var diagnosticWritten = new AtomicBoolean(); + var originalSqlFailure = new java.util.concurrent.atomic.AtomicReference(); + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat(rolledBack).isTrue(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + invocation.callRealMethod(); + diagnosticWritten.set(true); + return null; + }) + .when(joinOperationRepository) + .recordAttemptFailure( + fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + org.mockito.Mockito.doAnswer( + invocation -> { + var lockedRows = invocation.callRealMethod(); + if (failOnce.compareAndSet(true, false)) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + // The initial available read and real policy UPDATE have already run in this tx. + var transientPolicy = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + assertThat(transientPolicy.entitlementAuthorityAvailability()) + .isEqualTo("AVAILABLE"); + assertThat(transientPolicy.allowPublicJoin()).isTrue(); + assertThat(transientPolicy.entitlementVersion()).isEqualTo(1L); + assertThat(transientPolicy.requestDigest()).startsWith("sha256:"); + var independentRead = new TransactionTemplate(transactionManager); + independentRead.setPropagationBehavior( + org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); + independentRead.executeWithoutResult( + status -> { + var committedIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + assertThat(committedIntent.status()).isEqualTo("PENDING"); + assertThat(committedIntent.requestDigest()).isNull(); + assertThat(committedIntent.intentDigest()) + .isEqualTo(transientPolicy.intentDigest()); + }); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + rolledBack.set(status == STATUS_ROLLED_BACK); + } + }); + try { + // A real PostgreSQL error poisons this physical owner transaction; no savepoint. + dsl.fetch("SELECT 1 / 0"); + throw new AssertionError("PostgreSQL division by zero must fail"); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + originalSqlFailure.set(ex); + throw ex; + } + } + return lockedRows; + }) + .when(subscriptionRepository) + .findByTenantIdForUpdate(fixture.tenantId()); + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(originalSqlFailure.get()).isNotNull(); + assertThat(sqlState(originalSqlFailure.get())).isEqualTo("22012"); + assertThat(rolledBack).isTrue(); + assertThat(diagnosticWritten).isTrue(); + org.mockito.Mockito.verify(joinOperationRepository) + .recordAttemptFailure( + fixture.caller().requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + assertPublicJoinUnboundPending(fixture, "ENTITLEMENT_UNAVAILABLE", "UNAVAILABLE"); + String originalIntent = + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest(); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + + var recovered = publicJoin(fixture); + assertThat(recovered.success()).isTrue(); + assertThat(recovered.replayed()).isFalse(); + assertThat(recovered.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat( + joinOperationRepository.find(fixture.caller().requestId()).orElseThrow().intentDigest()) + .isEqualTo(originalIntent); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + var committed = publicJoinState(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(booleans = {false, true}) + void publicJoinTerminalEntitlementOutagePreservesOriginalBytes(boolean storageFailure) { + var fixture = publicJoinFixture(); + var originalResult = publicJoin(fixture); + assertThat(originalResult.success()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); + var outage = new AtomicBoolean(true); + var sqlFailure = new java.util.concurrent.atomic.AtomicReference(); + if (storageFailure) { + org.mockito.Mockito.doAnswer( + invocation -> { + var rows = invocation.callRealMethod(); + if (outage.get()) { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + try { + dsl.fetch("SELECT 1 / 0"); + throw new AssertionError("PostgreSQL division by zero must fail"); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException ex) { + sqlFailure.set(ex); + throw ex; + } + } + return rows; + }) + .when(subscriptionRepository) + .findByTenantIdForUpdate(fixture.tenantId()); + } else { + subscriptionRepository.deleteByAccountId(fixture.accountId(), fixture.tenantId()); + } + + var unavailable = publicJoin(fixture); + + assertThat(unavailable.success()).isFalse(); + assertThat(unavailable.replayed()).isFalse(); + assertThat(unavailable.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(unavailable.outcomeCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + if (storageFailure) { + assertThat(sqlFailure.get()).isNotNull(); + assertThat(sqlState(sqlFailure.get())).isEqualTo("22012"); + } + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + + outage.set(false); + if (!storageFailure) { + subscription.setId(null); + subscriptionRepository.save(subscription); + } + var replay = publicJoin(fixture); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.accountId()).isEqualTo(originalResult.accountId()); + assertThat(replay.membershipId()).isEqualTo(originalResult.membershipId()); + assertThat(replay.membershipVersion()).isEqualTo(originalResult.membershipVersion()); + assertThat(replay.membershipAuthorityGeneration()) + .isEqualTo(originalResult.membershipAuthorityGeneration()); + assertThat(replay.outcomeCode()).isEqualTo(originalResult.outcomeCode()); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + } + + @Test + void publicJoinChangedAvailablePolicyPreservesTheOriginalTerminalBytes() { + var fixture = publicJoinFixture(); + assertThat(publicJoin(fixture).success()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var originalEvidence = publicJoinOriginalEvidence(fixture); + var original = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + var subscription = subscriptionRepository.findByTenantId(fixture.tenantId()).getFirst(); + UUID originalGeneration = subscription.getTenantAuthorityGeneration(); + subscription.setStatus("trialing"); + subscriptionRepository.save(subscription); + assertThat(subscription.getEntitlementVersion()).isEqualTo(original.entitlementVersion() + 1L); + assertThat(subscription.getTenantAuthorityGeneration()).isNotEqualTo(originalGeneration); + var available = + accountService.getTenantEntitlementsForRuntime( + fixture.tenantId(), "changed-policy-" + fixture.caller().requestId()); + assertThat(available.gameplayAvailable()).isTrue(); + assertThat(available.allowPublicJoin()).isTrue(); + + var conflict = publicJoin(fixture); + + assertThat(conflict.success()).isFalse(); + assertThat(conflict.replayed()).isFalse(); + assertThat(conflict.accountId()).isEqualTo(fixture.accountUuid()); + assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertThat(publicJoinOriginalEvidence(fixture)).isEqualTo(originalEvidence); + assertPublicJoinCommittedOnce(fixture); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sql) { + return sql.getSQLState(); + } + } + return null; + } + + private void assertPublicJoinUnboundPending( + PublicJoinFixture fixture, String failureCode, String availability) { + var operation = joinOperationRepository.find(fixture.caller().requestId()).orElseThrow(); + var scope = connectScopeRepository.find(fixture.connectScopeId()).orElseThrow(); + assertThat(operation.accountId()).isEqualTo(fixture.accountId()); + assertThat(operation.tenantId()).isEqualTo(fixture.tenantId()); + assertThat(operation.callerBinding()).isEqualTo(fixture.caller().sessionId()); + assertThat(operation.scopeTokenHash()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + fixture.connectScopeId())); + assertThat(operation.connectScopeDigest()).isEqualTo(scope.snapshotDigest()); + assertThat(operation.intentDigestVersion()).isEqualTo(1); + assertThat(operation.intentDigest()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.intent( + fixture.caller().requestId(), scope, fixture.caller().sessionId())); + assertThat(operation.status()).isEqualTo("PENDING"); + assertThat(operation.outcome()).isNull(); + assertThat(operation.requestDigest()).isNull(); + assertThat(operation.requestDigestVersion()).isNull(); + assertThat(operation.allowPublicJoin()).isNull(); + assertThat(operation.entitlementVersion()).isNull(); + assertThat(operation.membershipId()).isNull(); + assertThat(operation.membershipVersion()).isNull(); + assertThat(operation.membershipAuthorityGeneration()).isNull(); + assertThat(operation.entitlementAuthorityAvailability()).isEqualTo(availability); + assertThat(operation.lastAttemptAuthorityAvailability()).isEqualTo(availability); + assertThat(operation.lastAttemptFailureCode()).isEqualTo(failureCode); + assertThat(publicJoinMembershipCount(fixture)).isZero(); + assertThat(publicJoinAuditCount(fixture)).isZero(); + } + + private List publicJoinOriginalEvidence(PublicJoinFixture fixture) { + assertThat(jwtUtil.parseToken(fixture.connectScopeId()).getPayload().getSubject()) + .isEqualTo(fixture.accountUuid()); + var account = accountRepository.findById(fixture.accountId()).orElseThrow(); + assertThat(account.getAccountUuid().toString()).isEqualTo(fixture.accountUuid()); + assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); + assertThat(account.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + return List.of( + dsl.resultQuery( + "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " + + "FROM account_authority_source_records s WHERE account_uuid = ?", + UUID.fromString(fixture.accountUuid())) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(e ORDER BY outbox_sequence)::text, '[]') " + + "FROM account_authority_outbox_events e WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + fixture.accountUuid()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(s)::text FROM account_connect_scope_records s WHERE scope_token_hash = ?", + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.tokenHash( + fixture.connectScopeId())) + .fetchOne(0, String.class)); + } + private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { var committed = new AtomicBoolean(); var readbackDropped = new AtomicBoolean(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 030cdb497a..cd901f9217 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verifyNoInteractions; @@ -85,8 +86,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; @@ -986,7 +989,7 @@ void closedPublicJoinRetainsFailureAndCannotCreateMembershipOrAudit() { service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(unavailableAuthorityReplay.success()); assertFalse(unavailableAuthorityReplay.replayed()); - assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityReplay.outcomeCode()); assertEquals(storedDeniedOperation, retainedOperation.get()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); @@ -1066,7 +1069,7 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers service.joinPublicProduction(bootstrap.bootstrapToken(), request); assertFalse(unavailableAuthorityRetry.success()); assertFalse(unavailableAuthorityRetry.replayed()); - assertEquals("AUTH_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthorityRetry.outcomeCode()); assertEquals(committedOperation, retainedOperation.get()); assertEquals(membership, joinedMembership.get()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) @@ -1083,8 +1086,9 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers } @ParameterizedTest - @CsvSource({"false", "true"}) - void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + @MethodSource("unavailableJoinReads") + void unavailableEntitlementRetainsJoinReceiptAndRecoversOnce( + boolean lockedRead, UnavailableEntitlement failure) { Account account = new Account(); account.setId(11L); setPersistedAuthenticationIdentity(account); @@ -1118,14 +1122,17 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou retainJoinEvidence(retainedScope, retainedOperation); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + AtomicBoolean authorityRecovered = new AtomicBoolean(); when(subscriptionRepository.findByTenantId(7L)) - .thenReturn( - ambiguous - ? java.util.List.of(new Subscription(), new Subscription()) - : java.util.List.of(), - java.util.List.of(recovered)); + .thenAnswer( + invocation -> + lockedRead || authorityRecovered.get() + ? java.util.List.of(recovered) + : failure.rows()); when(subscriptionRepository.findByTenantIdForUpdate(7L)) - .thenReturn(java.util.List.of(recovered)); + .thenAnswer( + invocation -> authorityRecovered.get() ? java.util.List.of(recovered) : failure.rows()); + org.mockito.Mockito.clearInvocations(accountConnectScopeRepository); JoinPublicProductionRequest request = new JoinPublicProductionRequest(connectScopeId, "join-unavailable-1"); @@ -1138,11 +1145,39 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); assertNotNull(retainedOperation.get().intentDigest()); - assertEquals(null, retainedOperation.get().requestDigest()); - assertEquals(null, retainedOperation.get().requestDigestVersion()); - assertEquals(null, retainedOperation.get().allowPublicJoin()); - assertEquals(null, retainedOperation.get().entitlementVersion()); + String intentDigest = retainedOperation.get().intentDigest(); + String boundDigest = retainedOperation.get().requestDigest(); + if (lockedRead) { + assertEquals( + net.firedevops.firemud.accountservice.dto.AccountJoinDigest.request( + retainedScope.get(), retainedOperation.get().callerBinding(), true, 1L), + boundDigest); + assertEquals(1, retainedOperation.get().requestDigestVersion()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertEquals("AVAILABLE", retainedOperation.get().entitlementAuthorityAvailability()); + } else { + assertNull(boundDigest); + assertNull(retainedOperation.get().requestDigestVersion()); + assertNull(retainedOperation.get().allowPublicJoin()); + assertNull(retainedOperation.get().entitlementVersion()); + } + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + JoinPublicProductionResult stillUnavailable = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertEquals("ENTITLEMENT_UNAVAILABLE", stillUnavailable.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + assertEquals(lockedRead ? Boolean.TRUE : null, retainedOperation.get().allowPublicJoin()); + assertEquals( + lockedRead ? Long.valueOf(1L) : null, retainedOperation.get().entitlementVersion()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + + authorityRecovered.set(true); JoinPublicProductionResult retriedAfterRecovery = service.joinPublicProduction(bootstrap.bootstrapToken(), request); @@ -1153,6 +1188,14 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou assertEquals(1L, retainedOperation.get().entitlementVersion()); assertEquals(true, retainedOperation.get().allowPublicJoin()); assertNotNull(retainedOperation.get().requestDigest()); + assertEquals(intentDigest, retainedOperation.get().intentDigest()); + if (lockedRead) { + assertEquals(boundDigest, retainedOperation.get().requestDigest()); + } + JoinPublicProductionResult replay = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertTrue(replay.success()); + assertTrue(replay.replayed()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.times(1)) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verify(accountAuditOutboxRepository, org.mockito.Mockito.times(1)) @@ -1162,10 +1205,324 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou org.mockito.ArgumentMatchers.eq(7L), org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), org.mockito.ArgumentMatchers.contains("join-unavailable-1")); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify( + subscriptionRepository, org.mockito.Mockito.times(lockedRead ? 4 : 2)) .findByTenantIdForUpdate(7L); } + private static java.util.stream.Stream unavailableJoinReads() { + return java.util.stream.Stream.of(false, true) + .flatMap( + locked -> + java.util.Arrays.stream(UnavailableEntitlement.values()) + .filter(failure -> failure.cause == null) + .map(failure -> Arguments.of(locked, failure))); + } + + private static java.util.stream.Stream storageJoinReads() { + return java.util.stream.Stream.of(false, true) + .flatMap( + locked -> + java.util.Arrays.stream(UnavailableEntitlement.values()) + .filter(failure -> failure.cause != null) + .map(failure -> Arguments.of(locked, failure))); + } + + @ParameterizedTest + @MethodSource("storageJoinReads") + void joinStorageOutageRollsBackBeforeRecordingFailureAndRecoversOriginalOnce( + boolean lockedRead, UnavailableEntitlement failure) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + AtomicBoolean recovered = new AtomicBoolean(); + Subscription available = new Subscription(); + available.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenAnswer( + invocation -> lockedRead || recovered.get() ? List.of(available) : failure.rows()); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer(invocation -> recovered.get() ? List.of(available) : failure.rows()); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + org.mockito.Mockito.clearInvocations( + transactionManager, accountConnectScopeRepository, accountJoinOperationRepository); + var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); + + var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); + + assertFalse(unavailable.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("UNAVAILABLE", retainedOperation.get().lastAttemptAuthorityAvailability()); + String originalIntent = retainedOperation.get().intentDigest(); + assertNotNull(originalIntent); + var order = org.mockito.Mockito.inOrder(transactionManager, accountJoinOperationRepository); + order.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + order + .verify(transactionManager) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); + order.verify(accountJoinOperationRepository).findForUpdate(request.requestId()); + order + .verify(accountJoinOperationRepository) + .recordAttemptFailure(request.requestId(), "UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE"); + order.verify(transactionManager).commit(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + // AtomicReference fixtures do not physically roll back policy writes; PostgreSQL proves that. + recovered.set(true); + var joined = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(joined.success()); + assertFalse(joined.replayed()); + assertEquals(originalIntent, retainedOperation.get().intentDigest()); + var committed = retainedOperation.get(); + assertTrue(service.joinPublicProductionFromGameSession(directTextCaller(), request).replayed()); + assertEquals(committed, retainedOperation.get()); + org.mockito.Mockito.verify(accountTenantMembershipRepository) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(accountAuditOutboxRepository) + .append( + org.mockito.ArgumentMatchers.any(UUID.class), + org.mockito.ArgumentMatchers.eq("tenant"), + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq("ACCOUNT_JOINED_PUBLIC_PRODUCTION"), + org.mockito.ArgumentMatchers.anyString()); + } + + @ParameterizedTest + @MethodSource("terminalJoinReadFailures") + void terminalJoinEntitlementOutagePreservesCompleteOriginal( + UnavailableEntitlement failure, String programmingFault) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + Subscription available = new Subscription(); + available.setStatus("active"); + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenReturn(List.of(available)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + when(accountTenantMembershipRepository.save(org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + AccountTenantMembership membership = invocation.getArgument(0); + membership.setId(701L); + return membership; + }); + var request = new JoinPublicProductionRequest(scope, directTextCaller().requestId()); + var originalResult = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(originalResult.success()); + var original = retainedOperation.get(); + var originalScope = retainedScope.get(); + AtomicBoolean recovered = new AtomicBoolean(); + when(subscriptionRepository.findByTenantIdForUpdate(7L)) + .thenAnswer( + invocation -> { + if (recovered.get()) { + return List.of(available); + } + if (programmingFault != null) { + throw entitlementProgrammingFault(programmingFault); + } + return failure.rows(); + }); + org.mockito.Mockito.clearInvocations( + accountTenantMembershipRepository, + accountAuditOutboxRepository, + accountJoinOperationRepository, + accountConnectScopeRepository); + + var unavailable = service.joinPublicProductionFromGameSession(directTextCaller(), request); + + assertFalse(unavailable.success()); + assertFalse(unavailable.replayed()); + assertEquals( + programmingFault == null ? "ENTITLEMENT_UNAVAILABLE" : "AUTH_UNAVAILABLE", + unavailable.outcomeCode()); + assertEquals(original, retainedOperation.get()); + assertEquals(originalScope, retainedScope.get()); + recovered.set(true); + var replay = service.joinPublicProductionFromGameSession(directTextCaller(), request); + assertTrue(replay.success()); + assertTrue(replay.replayed()); + assertEquals(originalResult.accountId(), replay.accountId()); + assertEquals(originalResult.membershipId(), replay.membershipId()); + assertEquals(originalResult.membershipVersion(), replay.membershipVersion()); + assertEquals( + originalResult.membershipAuthorityGeneration(), replay.membershipAuthorityGeneration()); + assertEquals(originalResult.outcomeCode(), replay.outcomeCode()); + assertEquals(original, retainedOperation.get()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .recordAttemptFailure( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verify(accountJoinOperationRepository, org.mockito.Mockito.never()) + .bindPolicyEvidence( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyBoolean()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + private static java.util.stream.Stream terminalJoinReadFailures() { + return java.util.stream.Stream.concat( + java.util.Arrays.stream(UnavailableEntitlement.values()) + .map(failure -> Arguments.of(failure, null)), + java.util.stream.Stream.of("mapping", "configuration") + .map(fault -> Arguments.of(null, fault))); + } + + @ParameterizedTest + @CsvSource({"false,mapping", "true,mapping", "false,configuration", "true,configuration"}) + void joinMappingAndConfigurationFaultsRetainUnexpectedFailureBoundary( + boolean lockedRead, String fault) { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + RuntimeException cause = entitlementProgrammingFault(fault); + if (lockedRead) { + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); + } else { + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + } + org.mockito.Mockito.clearInvocations(transactionManager, accountConnectScopeRepository); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId()))); + + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertSame(cause, unavailable.getCause()); + assertEquals("PENDING", retainedOperation.get().status()); + assertNotNull(retainedOperation.get().intentDigest()); + assertNull(retainedOperation.get().outcome()); + assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(transactionManager).rollback(org.mockito.ArgumentMatchers.any()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + @Test + void lateDuplicateRealmKeepsJoinPendingWithoutMembershipEffects() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String scope = + service + .issueDirectTextConnectScope(directTextCaller(), directTextTarget()) + .connectScopeId(); + var realm = gameSessionClient.listGameplayRealms("demo").getFirst(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(List.of(realm), List.of(realm, realm)); + org.mockito.Mockito.clearInvocations(subscriptionRepository, accountConnectScopeRepository); + + JoinPublicProductionResult result = + service.joinPublicProductionFromGameSession( + directTextCaller(), + new JoinPublicProductionRequest(scope, directTextCaller().requestId())); + + assertFalse(result.success()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(true, retainedOperation.get().allowPublicJoin()); + assertEquals(1L, retainedOperation.get().entitlementVersion()); + assertNotNull(retainedOperation.get().requestDigest()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.never()) + .findByTenantIdForUpdate(7L); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + + private static RuntimeException entitlementProgrammingFault(String fault) { + return "mapping".equals(fault) + ? new org.jooq.exception.MappingException("subscription mapping fault") + : new org.jooq.exception.ConfigurationException("subscription configuration fault"); + } + + private enum UnavailableEntitlement { + MISSING, + AMBIGUOUS, + NULL_LIST, + NULL_ROW, + ZERO_VERSION, + NEGATIVE_VERSION, + JOOQ_STORAGE(new org.jooq.exception.DataAccessException("subscription store unavailable")), + SPRING_STORAGE(new DataAccessResourceFailureException("subscription store unavailable")); + + private final RuntimeException cause; + + UnavailableEntitlement() { + this(null); + } + + UnavailableEntitlement(RuntimeException cause) { + this.cause = cause; + } + + private List rows() { + if (cause != null) { + throw cause; + } + return switch (this) { + case MISSING -> List.of(); + case AMBIGUOUS -> List.of(new Subscription(), new Subscription()); + case NULL_LIST -> null; + case NULL_ROW -> java.util.Collections.singletonList(null); + case ZERO_VERSION, NEGATIVE_VERSION -> { + Subscription invalid = new Subscription(); + invalid.setStatus("active"); + invalid.setEntitlementVersion(this == ZERO_VERSION ? 0L : -1L); + yield List.of(invalid); + } + default -> throw new IllegalStateException("Storage failure must have a cause"); + }; + } + } + @Test void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); @@ -1414,7 +1771,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { assertFalse(unavailableAuthority.success()); assertFalse(unavailableAuthority.replayed()); - assertEquals("AUTH_UNAVAILABLE", unavailableAuthority.outcomeCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailableAuthority.outcomeCode()); assertEquals(storedFailure, retainedOperation.get()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); @@ -3600,21 +3957,31 @@ void getTenantMembershipForRuntimeRejectsCrossTenantAccount() { assertTrue(!dto.gameplayAdmissionAllowed()); } - @Test - void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions() { + @ParameterizedTest + @CsvSource({ + "active,true,true", + "trialing,true,true", + "past_due,true,true", + "grace,true,false", + "canceled,false,false", + "unknown,false,false" + }) + void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions( + String status, boolean gameplayAvailable, boolean allowPublicJoin) { Subscription active = new Subscription(); active.setId(31L); active.setTenantId(7L); - active.setStatus("active"); + active.setStatus(status); + active.setEntitlementVersion(9L); when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); var dto = service.getTenantEntitlementsForRuntime(7L, "req-2"); assertEquals(7L, dto.tenantId()); - assertTrue(dto.gameplayAvailable()); - assertTrue(dto.allowPublicJoin()); - assertEquals(1L, dto.entitlementVersion()); - assertEquals(1L, dto.tenantBillingSequence()); + assertEquals(gameplayAvailable, dto.gameplayAvailable()); + assertEquals(allowPublicJoin, dto.allowPublicJoin()); + assertEquals(9L, dto.entitlementVersion()); + assertEquals(9L, dto.tenantBillingSequence()); assertNotNull(dto.evaluatedAt()); } @@ -3731,6 +4098,30 @@ void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { assertEquals(result.connectScopeExpiresAt(), retained.getValue().connectScopeExpiresAt()); } + @Test + void graceAllowsDirectScopeDiscoveryWithoutPublicJoinAuthority() { + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + Subscription grace = new Subscription(); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(List.of(grace)); + + var entitlement = service.getTenantEntitlementsForRuntime(7L, "grace-discovery"); + DirectTextJoinScope scope = + service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()); + + assertTrue(entitlement.gameplayAvailable()); + assertFalse(entitlement.allowPublicJoin()); + assertNotNull(scope.connectScopeId()); + org.mockito.Mockito.verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions( + accountJoinOperationRepository, + accountTenantMembershipRepository, + accountAuditOutboxRepository); + } + @Test void bothScopeProducersBindPersistedUuidWhileRetainedRowsKeepPrivateAccountKey() { Account account = directTextAccount(); @@ -3807,11 +4198,10 @@ void scopeReaderOwnerFailureIsUnavailableAndNumericScopesNeverReachOwnerLookup() assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); } - @Test - void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { - DataAccessResourceFailureException cause = - new DataAccessResourceFailureException("subscription store unavailable"); - when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + @ParameterizedTest + @EnumSource(UnavailableEntitlement.class) + void runtimeAndDirectScopeTreatUnsafeEntitlementAsUnavailable(UnavailableEntitlement failure) { + when(subscriptionRepository.findByTenantId(7L)).thenAnswer(invocation -> failure.rows()); AuthenticationException exception = assertThrows( @@ -3819,7 +4209,41 @@ void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - assertEquals(cause, exception.getCause()); + assertSame(failure.cause, exception.getCause()); + + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AuthenticationException scopeFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget())); + assertEquals("ENTITLEMENT_UNAVAILABLE", scopeFailure.getCode()); + assertSame(failure.cause, scopeFailure.getCause()); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); + } + + @ParameterizedTest + @ValueSource(strings = {"mapping", "configuration"}) + void runtimeAndDirectScopePropagateEntitlementProgrammingFaults(String fault) { + RuntimeException cause = entitlementProgrammingFault(fault); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + assertSame( + cause, + assertThrows( + cause.getClass(), () -> service.getTenantEntitlementsForRuntime(7L, "req-fault"))); + Account account = directTextAccount(); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + assertSame( + cause, + assertThrows( + cause.getClass(), + () -> service.issueDirectTextConnectScope(directTextCaller(), directTextTarget()))); + org.mockito.Mockito.verify(accountConnectScopeRepository, org.mockito.Mockito.never()) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + verifyNoInteractions(accountTenantMembershipRepository, accountAuditOutboxRepository); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index 32c37d563f..ec2ee9f19f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -78,21 +78,23 @@ public TextCommandInterpretationResult handle( + "LOGIN \n" + "Request a one-time email login code when the account allows it.\n" + "Use LOGON as an alias if your client expects it.\n" - + "After login, use PLAY [realm] [character]."); + + "After login, use PLAY [realm] [character], naming a known " + + "character when needed."); case "PLAY" -> success( "PLAY [realm] [character]\n" - + "Select the world to enter, optionally name a visible realm, and optionally choose a character."); + + "Select the world to enter, optionally name a visible realm, and use a known " + + "character name when selecting a character."); case "REALMS" -> success( "REALMS \n" + "List visible realms for the selected world.\n" - + "Use this before CHARS or PLAY when a world exposes more than one realm."); + + "Use this before PLAY when a world exposes more than one realm."); case "CHARS" -> success( - "CHARS [realm]\n" - + "List visible characters for the selected world and realm.\n" - + "Use REALMS first when the world exposes more than one realm."); + "CHARS\n" + + "Character browsing is unavailable. Use PLAY [realm] " + + "with a known character name."); case "WHO" -> success( "WHO\n" @@ -226,6 +228,8 @@ private ResolvedHelpTopic canonicalTopic(String topic, Optional case "HELP" -> "HELP"; case "LOGIN", "LOGON" -> "LOGIN"; case "PLAY" -> "PLAY"; + case "REALMS" -> "REALMS"; + case "CHARS" -> "CHARS"; case "WHO" -> "WHO"; case "STATUS", "STAT" -> "STATUS"; case "FRIENDS" -> "FRIENDS"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 8d57edfa9e..5c4608c5ce 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1055,9 +1055,7 @@ private String characterSelectionMessage( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { return "Selection required. Use " + playUsage(selectedWorld, selectedRealm) - + " or browse " - + charsUsage(selectedWorld, selectedRealm) - + " first."; + + " with a known character name."; } private PlayCommandHandlingResult characterSelectionRequiredFailure( @@ -1074,9 +1072,7 @@ private PlayCommandHandlingResult characterSelectionRequiredFailure( "realmSlug", selectedRealm.slug(), "playUsage", - playUsage(selectedWorld, selectedRealm), - "charsUsage", - charsUsage(selectedWorld, selectedRealm)), + playUsage(selectedWorld, selectedRealm)), tenantTag, Long.toString(selectedRealm.gameInstanceId()), null, @@ -1103,13 +1099,6 @@ private String playUsage( + " "; } - private String charsUsage( - GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { - return "CHARS " - + selectedWorld.slug() - + (selectedRealm.publicProductionRealm() ? "" : " " + selectedRealm.slug()); - } - private record ResolvedPlaySelection( String worldSelector, String explicitRealmSelector, String characterSelector) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 222a1dd56b..66f5dd227d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -2,10 +2,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -20,13 +16,9 @@ @Component public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; - private final EntityManagementClient entityManagementClient; - public WorldsCommandHandler( - GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { + public WorldsCommandHandler(GameplayWorldCatalog worldCatalog) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); } public WorldsViewOutput browseView() { @@ -62,47 +54,14 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.realmSelectionRequired(world.slug()); } - GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); - ListCharactersByAccountResponse response = - entityManagementClient.listCharactersByAccount( - Long.toString(realm.tenantId()), - sessionContext.accountId(), - Long.toString(realm.gameInstanceId()), - toPlayableStateScope(realm)); - if (response.hasError()) { - return CharacterBrowseResult.unavailable(); - } - java.util.List entries = - new java.util.ArrayList<>(response.getCharactersCount()); - for (int i = 0; i < response.getCharactersCount(); i++) { - net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); - if (!sessionContext.accountId().equals(character.getAccountId()) - || !Long.toString(realm.tenantId()).equals(character.getTenantId())) { - return CharacterBrowseResult.unavailable(); - } - entries.add( - new CharacterBrowseViewOutput.CharacterEntry( - i + 1, character.getId(), character.getName(), character.getLevel())); - } - return CharacterBrowseResult.success( - new CharacterBrowseViewOutput( - world.slug(), - realm.slug(), - realm.stateScope(), - realm.characterCreationPolicy(), - entries)); + return CharacterBrowseResult.unavailable(); } public sealed interface CharacterBrowseResult - permits CharacterBrowseResult.Success, - CharacterBrowseResult.InvalidWorld, + permits CharacterBrowseResult.InvalidWorld, CharacterBrowseResult.InvalidRealm, CharacterBrowseResult.RealmSelectionRequired, CharacterBrowseResult.Unavailable { - static CharacterBrowseResult success(CharacterBrowseViewOutput output) { - return new Success(output); - } - static CharacterBrowseResult invalidWorld() { return new InvalidWorld(); } @@ -119,8 +78,6 @@ static CharacterBrowseResult unavailable() { return new Unavailable(); } - record Success(CharacterBrowseViewOutput output) implements CharacterBrowseResult {} - record InvalidWorld() implements CharacterBrowseResult {} record InvalidRealm(String worldSlug) implements CharacterBrowseResult {} @@ -129,16 +86,4 @@ record RealmSelectionRequired(String worldSlug) implements CharacterBrowseResult record Unavailable() implements CharacterBrowseResult {} } - - private PlayableStateScope toPlayableStateScope(GameplayWorldCatalog.RealmView realm) { - String scope = - realm.stateScope() == null - ? "" - : realm.stateScope().trim().toUpperCase(java.util.Locale.ROOT); - return switch (scope) { - case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - default -> PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED; - }; - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index f23d704bd1..89766acfb7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -79,29 +79,26 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r request.command().characterBrowsePayload().orElseThrow(); return switch (worldsHandler.browseCharacters( request.sessionContext().orElseThrow(), payload.worldSelector(), payload.realmSelector())) { - case WorldsCommandHandler.CharacterBrowseResult.Success success -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( - success.output()))); case WorldsCommandHandler.CharacterBrowseResult.InvalidWorld ignored -> errorResult( "INVALID_ARGUMENT", "CHARS requires a valid world selector. Use WORLDS first."); case WorldsCommandHandler.CharacterBrowseResult.InvalidRealm invalidRealm -> errorResult( "INVALID_ARGUMENT", - "Use REALMS " + invalidRealm.worldSlug() + " to choose a visible realm first."); + "Use REALMS " + invalidRealm.worldSlug() + " to choose a visible realm."); case WorldsCommandHandler.CharacterBrowseResult.RealmSelectionRequired realmSelectionRequired -> errorResult( "PLAY_SELECTION_REQUIRED", - "Selection required. Use REALMS " + "Selection required. Choose a visible realm with REALMS " + realmSelectionRequired.worldSlug() - + " before CHARS."); + + "."); case WorldsCommandHandler.CharacterBrowseResult.Unavailable ignored -> errorResult( - "CHARACTER_LIST_UNAVAILABLE", "Character list unavailable. Retry CHARS shortly."); + "CHARACTER_LIST_UNAVAILABLE", + "Character browsing is unavailable. Use PLAY [realm] " + + "with a known character name.", + "error.chars.unavailable"); }; } @@ -111,6 +108,15 @@ private TextCommandInterpretationResult errorResult(String code, String message) List.of(net.firedevops.firemud.gamesession.presentation.PlayerOutput.error(code, message))); } + private TextCommandInterpretationResult errorResult( + String code, String message, String messageKey) { + return new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.failure(code, message), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( + code, message, messageKey, java.util.Map.of()))); + } + private void publishCommandEvent(SessionContext context, TextCommand command) { try { scriptEventPublisher.publishCommandEvent( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java index 8d1ff2ac5f..bdd527a7f1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java @@ -62,13 +62,15 @@ public void clearGameplayBinding(SessionContext context, String clearReason) { @Override public void recordDisconnected(long sessionId, AccountRecentPresenceDisposition disposition) { - sessionRoutingNormalizationService - .resolveProjectedSessionContext(Long.toString(sessionId)) - .filter(SessionContext::hasGameplayRegionBindingOrFalse) - .ifPresent( - context -> - scriptEventPublisher.publishRegionExitEvent( - context, disconnectEventId(context, disposition), disposition.name())); + if (disposition != AccountRecentPresenceDisposition.TAKEOVER) { + sessionRoutingNormalizationService + .resolveProjectedSessionContext(Long.toString(sessionId)) + .filter(SessionContext::hasGameplayRegionBindingOrFalse) + .ifPresent( + context -> + scriptEventPublisher.publishRegionExitEvent( + context, disconnectEventId(context, disposition), disposition.name())); + } accountRecentPresenceService.recordDisconnect(sessionId, disposition); gameplayPresenceService.removeBySessionId(sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java index 9354d34e66..680ec8a2d2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java @@ -8,15 +8,10 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.gamesession.command.text.GameplayLoggingContext; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionIdParsing; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; @@ -31,35 +26,28 @@ @GrpcService public final class TcpProxyServiceImpl extends TcpProxyServiceGrpc.TcpProxyServiceImplBase { private static final Logger logger = LoggingUtil.getLogger(TcpProxyServiceImpl.class); - private static final String SUSPENDED_STATUS = "SUSPENDED"; private static final String DUPLICATE_DISCONNECT_METRIC = "gamesession.notifydisconnect.duplicate"; private static final String MISSING_CONTEXT_METRIC = "gamesession.notifydisconnect.missing_context"; private final GameInstanceRepository repository; - private final SessionStateService sessionStateService; private final MeterRegistry meterRegistry; private final PingService pingService; private final DisconnectDeduplicationService disconnectDeduplicationService; - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected repository/services are internal Spring collaborators") public TcpProxyServiceImpl( GameInstanceRepository repository, - SessionStateService sessionStateService, MeterRegistry meterRegistry, PingService pingService, - DisconnectDeduplicationService disconnectDeduplicationService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService) { + DisconnectDeduplicationService disconnectDeduplicationService) { this.repository = repository; - this.sessionStateService = sessionStateService; this.meterRegistry = meterRegistry; this.pingService = pingService; this.disconnectDeduplicationService = disconnectDeduplicationService; - this.gameplayPresenceLifecycleService = gameplayPresenceLifecycleService; } @Override @@ -102,62 +90,18 @@ private ErrorDetail handleNotifyDisconnect( } } - if (StringUtils.hasText(request.getSessionId())) { - SessionIdParsing.parse(request.getSessionId()) - .optionalValue() - .ifPresent( - sessionId -> - gameplayPresenceLifecycleService.recordDisconnected( - sessionId, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); - } if (!StringUtils.hasText(gameInstanceIdText) || !StringUtils.hasText(request.getTenantId())) { meterRegistry.counter(MISSING_CONTEXT_METRIC).increment(); return GrpcAppErrors.ok("Disconnect recorded (no proxy bootstrap metadata)"); } - SessionValidationResult validation = - validateGameInstance(gameInstanceIdText, request.getTenantId()); - if (validation.hasError()) { - return validation.errorDetail(); - } - GameInstance instance = validation.instance(); - GameInstanceDto suspendedState = - new GameInstanceDto( - instance.getId(), - instance.getTenantId(), - instance.getRuntimeVersion(), - instance.getScriptPatchVersion(), - instance.getScriptPatchBaseVersionId(), - instance.getScriptPinEpoch(), - instance.getScriptPatchPinnedControlPlaneRequestId(), - instance.getGameTemplateId(), - instance.getLaunchDescriptorId(), - instance.getVersionId(), - instance.getReleaseBundleId(), - instance.getVersionStateEpoch(), - instance.getGenerationConfigRevision(), - instance.getRemapSetId(), - instance.getOwnerAccountId(), - SUSPENDED_STATUS); - try { - sessionStateService.saveState(suspendedState); - return GrpcAppErrors.ok("Disconnect recorded"); - } catch (RuntimeException ex) { - logger.error( - "Failed to save suspended session state tenantId={} gameInstanceId={} proxyConnectionId={} disconnectSequence={}", - request.getTenantId(), - gameInstanceIdText, - request.getProxyConnectionId(), - request.getDisconnectSequence(), - ex); - return GrpcAppErrors.error(meterRegistry, "INTERNAL", "Failed to update session state"); - } + return validateGameInstance(gameInstanceIdText, request.getTenantId()) + .orElseGet(() -> GrpcAppErrors.ok("Disconnect recorded")); } - private SessionValidationResult validateGameInstance( + private Optional validateGameInstance( String gameInstanceIdText, String tenantIdText) { if (!StringUtils.hasText(gameInstanceIdText) || !StringUtils.hasText(tenantIdText)) { - return SessionValidationResult.failed( - invalidArgumentError("gameInstanceId and tenantId are required")); + return Optional.of(invalidArgumentError("gameInstanceId and tenantId are required")); } try { long gameInstanceId = @@ -165,15 +109,15 @@ private SessionValidationResult validateGameInstance( long tenantId = ControlPlaneRequestParser.parsePositiveLong(tenantIdText, "tenantId"); Optional maybeInstance = repository.findById(gameInstanceId); if (maybeInstance.isEmpty()) { - return SessionValidationResult.failed(notFoundError("Game instance not found")); + return Optional.of(notFoundError("Game instance not found")); } GameInstance instance = maybeInstance.get(); if (!instance.getTenantId().equals(tenantId)) { - return SessionValidationResult.failed(invalidArgumentError("Tenant does not own session")); + return Optional.of(invalidArgumentError("Tenant does not own session")); } - return new SessionValidationResult(instance, null); + return Optional.empty(); } catch (IllegalArgumentException ex) { - return SessionValidationResult.failed(invalidArgumentError(ex.getMessage())); + return Optional.of(invalidArgumentError(ex.getMessage())); } } @@ -185,14 +129,4 @@ private ErrorDetail invalidArgumentError(String message) { private ErrorDetail notFoundError(String message) { return GrpcAppErrors.error(meterRegistry, logger, "NotifyDisconnect", "NOT_FOUND", message); } - - private record SessionValidationResult(GameInstance instance, ErrorDetail errorDetail) { - static SessionValidationResult failed(ErrorDetail errorDetail) { - return new SessionValidationResult(null, errorDetail); - } - - boolean hasError() { - return errorDetail != null; - } - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index b8193eabbc..5b5fbe48f4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -251,7 +251,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) outputs, resolveLocaleTag(session, sessionId), effectivePresentation); - maybeReplayScreenBufferAndRefreshLook( + maybeRefreshReconnectLook( session, sessionId, command, interpretation, maybeContext); maybeCloseAfterSuccessfulLogout(session, command, interpretation); } catch (SessionContextUnavailableException unavailable) { @@ -509,7 +509,7 @@ private void maybeAppendToScreenBuffer( replayEntries)); } - private void maybeReplayScreenBufferAndRefreshLook( + private void maybeRefreshReconnectLook( WebSocketSession session, String sessionId, TextCommand command, @@ -518,7 +518,7 @@ private void maybeReplayScreenBufferAndRefreshLook( throws IOException { boolean reconnectRestoreRequested = interpretation.reconnectRedrawRecommended() - || StringUtils.hasText(resolveConnectContext(session)); + || "first_party_web".equals(resolveConnectionMode(session)); if (command.type() != TextCommandType.PLAY || !interpretation.commandResult().accepted() || !reconnectRestoreRequested) { @@ -529,14 +529,9 @@ private void maybeReplayScreenBufferAndRefreshLook( .ifPresent( context -> { try (GameplayLoggingContext ignored = GameplayLoggingContext.from(context)) { - Optional maybeBuffer = - screenBufferService.get( - context.tenantId(), context.gameInstanceId(), context.characterId()); - if (maybeBuffer.isEmpty()) { - return; - } - maybeBuffer.ifPresent( - buffer -> sendReplayEntries(session, buffer, "screen buffer")); + // Private retained context stays closed until current generation, episode, + // and authorization evidence is qualified end to end. Retention is unchanged; + // reconnect recommendations and connect contexts alone are not replay authority. String localeTag = resolveLocaleTag(session, sessionId); PresentationProperties effectivePresentation = settingsResolver.presentation(context); @@ -545,7 +540,8 @@ private void maybeReplayScreenBufferAndRefreshLook( sendProjectedOutput( session, look, localeTag, effectivePresentation, "fresh LOOK"); } - if (effectivePresentation.prompt().emitAfterReconnectRestore()) { + if (effectivePresentation.prompt().enabled() + && effectivePresentation.prompt().emitAfterReconnectRestore()) { composePrompt(context) .ifPresent( prompt -> { @@ -558,37 +554,6 @@ private void maybeReplayScreenBufferAndRefreshLook( }); } - private void sendReplayChunk(WebSocketSession session, String text, String label) { - try (CombinedLoggingContext ignored = openLoggingContext(session)) { - try { - sendProtocolMessage(session, outputProjector.projectTranscriptChunk(session, label, text)); - } catch (IOException ex) { - logger.warn("Failed to send reconnect {}", label, ex); - } - } - } - - private void sendReplayEntries( - WebSocketSession session, ScreenBufferService.BufferedScreen buffer, String label) { - if (!outputProjector.isFirstPartyWeb(session) - || buffer.entries().stream() - .noneMatch(ScreenBufferService.BufferedEntry::hasStructuredOutput)) { - sendReplayChunk(session, buffer.protocolText(), label); - return; - } - for (ScreenBufferService.BufferedEntry entry : buffer.entries()) { - try (CombinedLoggingContext ignored = openLoggingContext(session)) { - try { - sendProtocolMessage( - session, outputProjector.projectTranscriptEntry(session, label, entry)); - } catch (IOException ex) { - logger.warn("Failed to send reconnect {}", label, ex); - return; - } - } - } - } - private void sendProjectedOutput( WebSocketSession session, PlayerOutput output, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index c9a85edc25..0b38c3c6a3 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -16,7 +16,8 @@ error.login.unavailable=Login is temporarily unavailable. error.play.invalid-argument=PLAY command requires a world selector. error.play.selection-required=Use WORLDS to browse available worlds, then PLAY [realm] [character]. error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} [character] or browse REALMS first. -error.play.character-selection-required=Selection required. Use {playUsage} or browse {charsUsage} first. +error.play.character-selection-required=Selection required. Use {playUsage} with a known character name. +error.chars.unavailable=Character browsing is unavailable. Use PLAY [realm] with a known character name. error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index b6692bab00..dbe946600d 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -16,7 +16,8 @@ error.login.unavailable=La connexion est temporairement indisponible. error.play.invalid-argument=La commande PLAY requiert un selecteur de monde. error.play.selection-required=Utilisez WORLDS pour parcourir les mondes disponibles, puis PLAY [realm] [character]. error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug} [character] ou consultez REALMS d’abord. -error.play.character-selection-required=Selection requise. Utilisez {playUsage} ou consultez {charsUsage} dabord. +error.play.character-selection-required=Sélection requise. Utilisez {playUsage} avec le nom d’un personnage connu. +error.chars.unavailable=La consultation des personnages n’est pas disponible. Utilisez PLAY [realm] avec le nom d’un personnage connu. error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 69367ab3b6..8d6c89cc22 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -180,7 +180,8 @@ void websocketReconnectAfterMoveKeepsDestinationRoomContext() throws Exception { LookTestFixtures.DESTINATION_ROOM_ID) .test(response.trim())); - List reconnectLook = runLookAfterReconnect(sessionId); + List reconnectLook = + runLookAfterReconnect(sessionId, LookTestFixtures.DESTINATION_ROOM_ID); assertThat(reconnectLook).hasSizeGreaterThanOrEqualTo(4); String combinedReconnect = String.join("\n", reconnectLook); assertThat(combinedReconnect).contains("OK LOGIN"); @@ -305,11 +306,18 @@ void websocketReconnectAfterStaleSessionFreshEntersGameplay() throws Exception { LookTestFixtures.DESTINATION_ROOM_ID) .test(response.trim())); - gameSession() - .bean(net.firedevops.firemud.gamesession.service.SessionContextService.class) - .deleteBySessionId(TENANT_ID, sessionId); - - List reconnectLook = runLookAfterReconnect(sessionId); + var contexts = + gameSession().bean(net.firedevops.firemud.gamesession.service.SessionContextService.class); + var staleContext = contexts.findBySessionId(sessionId).orElseThrow(); + assertThat(staleContext.roomInstanceId()).isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID); + contexts.deleteBySessionId(staleContext.tenantId(), staleContext.sessionId()); + assertThat(contexts.findBySessionId(staleContext.sessionId())).isEmpty(); + assertThat( + contexts.findByGameplayIdentity( + staleContext.tenantId(), staleContext.gameInstanceId(), staleContext.characterId())) + .isEmpty(); + + List reconnectLook = runLookAfterReconnect(sessionId, LookTestFixtures.ROOM_ID); assertThat(reconnectLook).hasSizeGreaterThanOrEqualTo(3); String combinedReconnect = String.join("\n", reconnectLook); assertThat(combinedReconnect).contains("OK LOGIN"); @@ -391,30 +399,10 @@ private List runQuickLookSequence(long sessionId) throws Exception { } private List runMoveThenDisconnect(long sessionId) throws Exception { - try (GameplayWebSocketScenarios.ReconnectScenario scenario = - GameplayWebSocketScenarios.reconnectAfterReady( - ignored -> - GameplayWebSocketScenarios.openGameplaySession( - gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), - "session-" + sessionId + "-first", - "session-" + sessionId + "-unused", - READY_LOOK_TEXT, - GameplayWebSocketScenarios.DisconnectMode.CLOSE, - client -> { - client.send("north"); - GameplayAsyncAssertions.assertEventually( - "canonical move transcript before reconnect close", - java.time.Duration.ofSeconds(5), - () -> { - try { - client.awaitCanonicalMoveOrLook(LookTestFixtures.DESTINATION_ROOM_ID); - return true; - } catch (Exception ex) { - return false; - } - }); - })) { - return scenario.firstResponses(); + try (GameplayWebSocketDriver client = openReadySession(sessionId)) { + client.send("north"); + client.awaitCanonicalMoveOrLook(LookTestFixtures.DESTINATION_ROOM_ID); + return client.responses(); } } @@ -424,33 +412,18 @@ private List runPlayThenDisconnect(long sessionId) throws Exception { } } - private List runLookAfterReconnect(long sessionId) throws Exception { - try (GameplayWebSocketScenarios.ReconnectScenario scenario = - GameplayWebSocketScenarios.reconnectAfterReady( + private List runLookAfterReconnect(long sessionId, String expectedRoomId) + throws Exception { + try (GameplayWebSocketDriver client = + GameplayWebSocketScenarios.openAdmitted( ignored -> GameplayWebSocketScenarios.openGameplaySession( gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), - "session-" + sessionId + "-first", "session-" + sessionId + "-reconnect", - READY_LOOK_TEXT, - GameplayWebSocketScenarios.DisconnectMode.CLOSE, - client -> { - client.send("north"); - client.awaitCanonicalMoveOrLook(LookTestFixtures.DESTINATION_ROOM_ID); - })) { - scenario.reconnecting().send("LOOK"); - scenario - .reconnecting() - .awaitResponseMatching( - response -> - GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( - LookTestFixtures.ROOM_ID) - .test(response.trim()) - || GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim()), - "reconnect look response"); - return scenario.reconnecting().responses(); + READY_LOOK_TEXT)) { + client.send("LOOK"); + client.awaitCanonicalLook(expectedRoomId); + return client.responses(); } } @@ -490,7 +463,8 @@ private GameplayWebSocketDriver openReadySession(long sessionId) throws Exceptio TENANT_ID, sessionId, READY_LOOK_TEXT, - "session-" + sessionId); + "session-" + sessionId, + java.util.Map.of("X-Firemud-Transport-Session-Id", Long.toString(sessionId))); } private URI gameSessionWebSocketUrl() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 0fce1096fc..ea58aac339 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.argThat; -import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; @@ -644,7 +643,8 @@ void freshLoginAfterLogoutDoesNotReplayStaleReconnectBuffer() throws Exception { } @Test - void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception { + void unexpectedDisconnectKeepsFreshReconnectLookButDoesNotReplayPrivateContext() + throws Exception { clearInvocations(screenBufferService); when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( @@ -666,16 +666,17 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { - client.awaitContains("RECONNECT REPLAY APPEARS"); + client.awaitContains("Room: Login Hall"); secondPayloads = client.responses(); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 1, java.time.Duration.ofSeconds(5)); assertThat(gameplayPresenceService.listConnectedByGameInstance(22L, 1L)) .anySatisfy(presence -> assertThat(presence.sessionId()).isEqualTo(42L)); } - assertThat(secondPayloads).anyMatch(payload -> payload.contains("RECONNECT REPLAY APPEARS")); + assertThat(secondPayloads).noneMatch(payload -> payload.contains("RECONNECT REPLAY APPEARS")); + assertThat(secondPayloads).anyMatch(payload -> payload.contains("Room: Login Hall")); assertThat(secondPayloads).anyMatch(payload -> payload.startsWith("OK PLAY")); - verify(screenBufferService, atLeastOnce()).get(22L, 1L, 123L); + verify(screenBufferService, never()).get(22L, 1L, 123L); verify(screenBufferService, never()).clear(22L, 1L, 123L); } @@ -801,14 +802,14 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { } @Test - void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { + void websocketLoginCanBrowseRealmsButCharsStaysUnavailableBeforePlay() throws Exception { List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); client.send("REALMS demo"); client.awaitStartsWith("OK REALMS"); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } @@ -820,17 +821,19 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) .anyMatch( + payload -> + payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE") + && payload.contains("known character name")); + assertThat(payloads) + .noneMatch( payload -> payload.startsWith("OK CHARS") - && payload.contains("Emberline [lvl 12]") - && payload.contains("Sora [lvl 7]") - && payload.contains("Realm state: shared, creation: allow_new")); + || payload.contains("Emberline [lvl") + || payload.contains("Sora [lvl")); verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); - verify(entityManagementClient) - .listCharactersByAccount( - "22", ACCOUNT_UUID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + verify(entityManagementClient, never()).listCharactersByAccount(any(), any(), any(), any()); } @Test @@ -936,16 +939,18 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() client.send("LOOK"); client.awaitStartsWith("ERROR PLAY_REQUIRED"); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); assertThat(payloads).anyMatch(payload -> payload.startsWith("OK PLAY")); assertThat(payloads).anyMatch(payload -> payload.startsWith("ERROR PLAY_REQUIRED")); - assertThat(payloads).anyMatch(payload -> payload.startsWith("OK CHARS")); - assertThat(payloads).anyMatch(payload -> payload.contains("CutoverArrival")); - org.mockito.Mockito.verify(entityManagementClient) + assertThat(payloads) + .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); + assertThat(payloads) + .noneMatch(payload -> payload.startsWith("OK CHARS") || payload.contains("CutoverArrival")); + org.mockito.Mockito.verify(entityManagementClient, never()) .listCharactersByAccount( "22", ACCOUNT_UUID, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 27a57c951d..ef49ce40bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -42,6 +42,30 @@ void helpDoesNotAdvertiseOrDescribeTheUnregisteredJoinCommand() { assertEquals("HELP_UNKNOWN_TOPIC", topic.commandResult().errorCode()); } + @Test + void helpBrowseGuidanceUsesKnownCharacterPlayAndDoesNotRecommendChars() { + TextCommandInterpretationResult realms = + handler.handle(new TextCommand(TextCommandType.HELP, List.of("realms"), "HELP realms")); + TextCommandInterpretationResult chars = + handler.handle(new TextCommand(TextCommandType.HELP, List.of("chars"), "HELP chars")); + TextCommandInterpretationResult play = + handler.handle(new TextCommand(TextCommandType.HELP, List.of("play"), "HELP play")); + + assertTrue(realms.commandResult().accepted()); + assertTrue(realms.outputs().get(0).text().contains("Use this before PLAY")); + assertFalse(realms.outputs().get(0).text().contains("CHARS")); + + assertTrue(chars.commandResult().accepted()); + assertFalse(chars.outputs().get(0).text().contains("CHARS ")); + assertTrue(chars.outputs().get(0).text().contains("Character browsing is unavailable.")); + assertTrue(chars.outputs().get(0).text().contains("PLAY [realm] ")); + assertTrue(chars.outputs().get(0).text().contains("known character name")); + assertFalse(chars.outputs().get(0).text().contains("List visible characters")); + + assertTrue(play.commandResult().accepted()); + assertTrue(play.outputs().get(0).text().contains("known character name")); + } + @Test void helpWhoTopicExplainsGameplayOnlyScope() { TextCommandInterpretationResult result = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 000d7536c0..828ea7b3e0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1108,7 +1108,7 @@ void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); assertThat(result.commandResult().errorMessage()) .isEqualTo( - "Selection required. Use PLAY sandbox preview or browse CHARS sandbox preview first."); + "Selection required. Use PLAY sandbox preview with a known character name."); } @Test @@ -2039,7 +2039,7 @@ private void verifyNoGameplayBindingSideEffects() { private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult result) { String expectedMessage = - "Selection required. Use PLAY demo or browse CHARS demo first."; + "Selection required. Use PLAY demo with a known character name."; assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); @@ -2052,8 +2052,7 @@ private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult resu assertThat(error.arguments()) .containsEntry("worldSlug", "demo") .containsEntry("realmSlug", "production") - .containsEntry("playUsage", "PLAY demo ") - .containsEntry("charsUsage", "CHARS demo"); + .containsEntry("playUsage", "PLAY demo "); } private static GameplayCommand command(String commandId, String commandName, String commandText) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 7d76a692ad..5f6118991d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -289,7 +289,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - worldsHandler = new WorldsCommandHandler(worldCatalog, entityManagementClient); + worldsHandler = new WorldsCommandHandler(worldCatalog); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = @@ -537,7 +537,8 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); - assertTrue(charsAfterCutover.commandResult().accepted()); + assertFalse(charsAfterCutover.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", charsAfterCutover.commandResult().errorCode()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index d2a3432b95..75666c49f2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -416,8 +416,7 @@ void setUp() { .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); - WorldsCommandHandler worldsHandler = - new WorldsCommandHandler(worldCatalog, entityManagementClient); + WorldsCommandHandler worldsHandler = new WorldsCommandHandler(worldCatalog); LookResult lookResult = LookResult.newBuilder() @@ -536,17 +535,21 @@ void realmsAreVisibleAfterLogin() { } @Test - void charsAreVisibleAfterLogin() { + void charsFailClosedAfterLoginWithoutReturningRoster() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "CHARS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("1) demo [lvl 12]")); - assertTrue( - renderedResponse("CHARS demo", interpretation) - .contains("Realm state: shared, creation: allow_new")); + assertFalse(interpretation.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", interpretation.commandResult().errorCode()); + assertEquals( + "ERROR CHARACTER_LIST_UNAVAILABLE Character browsing is unavailable. " + + "Use PLAY [realm] with a known character name.", + renderedResponse("CHARS demo", interpretation)); + verify(entityManagementClient, never()) + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index d575ecfa04..d0ae7b8153 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -4,28 +4,18 @@ import java.util.List; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; -import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class WorldsCommandHandlerTest { - private final EntityManagementClient entityManagementClient = - Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final WorldsCommandHandler handler = - new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + new WorldsCommandHandler(TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties)); @BeforeEach void setUp() { @@ -78,8 +68,7 @@ void browseRealmsToleratesNullRealmEnums() { .setCharacterCreationPolicy(null); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties)); RealmBrowseViewOutput response = localHandler.browseRealms("demo").orElseThrow(); @@ -88,159 +77,47 @@ void browseRealmsToleratesNullRealmEnums() { } @Test - void browseCharactersReturnsStructuredCharacterList() { - gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "1", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) - .setName("Emberline") - .setLevel(12) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build()) - .build()); - - WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", null); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.worldSlug()).isEqualTo("demo"); - assertThat(output.realmSlug()).isEqualTo("production"); - assertThat(output.stateScope()).isEqualTo("SHARED"); - assertThat(output.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); - assertThat(output.characters()).hasSize(1); - assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); - Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "1", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - } - - @Test - void browseCharactersUsesIsolatedStateRealmRoster() { - gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "41", - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("8001") - .setTenantId("22") - .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) - .setName("Forkline") - .setLevel(5) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - .build()) - .build()); - - WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", null); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.stateScope()).isEqualTo("ISOLATED"); - assertThat(output.characterCreationPolicy()).isEqualTo("COPIED_ONLY"); - assertThat(output.characters()) - .extracting(CharacterBrowseViewOutput.CharacterEntry::characterName) - .containsExactly("Forkline"); - Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "41", - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); - } - - @Test - void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { + void browseCharactersFailsClosedAfterValidWorldAndDefaultRealmResolution() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "1", - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + assertThat( + handler.browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); } @Test - void charsRejectsNumericOrMismatchedAccountOwnersWithoutReturningRoster() { - gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { + GameplayCatalogProperties.World demo = world("demo", 22L, 1L, false); + GameplayCatalogProperties.Realm preview = new GameplayCatalogProperties.Realm(); + preview.setSlug("preview"); + preview.setDisplayName("Preview Realm"); + preview.setTenantId(22L); + preview.setGameInstanceId(2L); + preview.setVisible(true); + preview.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); + preview.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); + demo.setRealms(List.of(demo.getRealms().getFirst(), preview)); + gameplayCatalogProperties.setWorlds(List.of(demo)); var actor = GameplayCommandTestFixtures.worldBrowseDemo(); - for (String owner : - List.of( - "123", - "00000000-0000-0000-0000-000000000000", - AccountRuntimeStubServer.accountUuidForTestFixture(124L))) { - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", actor.accountId(), "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId(owner) - .setName("Other")) - .build()); - assertThat(handler.browseCharacters(actor, "demo", null)) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); - } + + assertThat(handler.browseCharacters(actor, "missing", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + assertThat(handler.browseCharacters(actor, "demo", "hidden")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(handler.browseCharacters(actor, "demo", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.RealmSelectionRequired.class); + assertThat(handler.browseCharacters(actor, "demo", "preview")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); } @Test - void charsRejectsNonCanonicalCallerBeforeEntityRead() { + void charsRejectsNonCanonicalCallerBeforeCatalogSelection() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); var actor = new net.firedevops.firemud.gamesession.service.SessionContext( 1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"); assertThat(handler.browseCharacters(actor, "demo", null)) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); - Mockito.verifyNoInteractions(entityManagementClient); } private static GameplayCatalogProperties.World world( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index f8b0aea263..74b89b5522 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -1,28 +1,20 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; import java.util.List; import java.util.Optional; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; -import net.firedevops.firemud.test.AccountRuntimeStubServer; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { - private final EntityManagementClient entityManagementClient = - Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final ScriptEventPublisher scriptEventPublisher = @@ -30,8 +22,7 @@ class WorldsTextCommandDispatchHandlerTest { private final WorldsTextCommandDispatchHandler handler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient), + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties)), scriptEventPublisher); @Test @@ -55,7 +46,7 @@ void preparedJoinExplicitlyRefusesWithoutDiscoveryOrGameplayEffects() { output -> assertThat(output.text()) .isEqualTo("ERROR FEATURE_UNAVAILABLE JOIN is not available.")); - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(scriptEventPublisher); } @Test @@ -116,25 +107,8 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { } @Test - void publishesCommandEventForGameplayScopedCharsBrowse() { + void refusesCharacterBrowseWithoutPublishingCommandEvent() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); - when(entityManagementClient.listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "41", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId(AccountRuntimeStubServer.accountUuidForTestFixture(123L)) - .setName("Emberline") - .setLevel(12) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build()) - .build()); SessionContext context = GameplayCommandTestFixtures.helpCapabilityEmberline(7L); TextCommandInterpretationResult result = @@ -146,24 +120,13 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { Optional.of(context), Optional.empty())); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(CharacterBrowseViewOutput.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", - AccountRuntimeStubServer.accountUuidForTestFixture(123L), - "41", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "CHARS".equals(gameplayCommand.getCommandName()) - && "CHARS demo".equals(gameplayCommand.getCommandText()))); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo( + "Character browsing is unavailable. Use PLAY [realm] " + + "with a known character name."); + Mockito.verifyNoInteractions(scriptEventPublisher); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 3dad96e85a..bfc366cd06 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -862,6 +862,55 @@ void localizedErrorUsesConfiguredLocaleTemplate() { .isEqualTo("ERROR LOGIN_REQUIRED You must LOGIN first. Use LOGIN [secret]."); } + @Test + void localizedCharacterBrowseUnavailableErrorUsesConfiguredLocaleTemplate() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "fr", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + + String rendered = + renderer.render( + PlayerOutput.error( + "CHARACTER_LIST_UNAVAILABLE", + "fallback", + "error.chars.unavailable", + java.util.Map.of())); + + assertThat(rendered) + .isEqualTo( + "ERROR CHARACTER_LIST_UNAVAILABLE La consultation des personnages n’est pas " + + "disponible. Utilisez PLAY [realm] avec le nom d’un " + + "personnage connu."); + } + + @Test + void localizedPlayCharacterSelectionUsesKnownCharacterGuidance() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "fr", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L))); + + String rendered = + renderer.render( + PlayerOutput.error( + "PLAY_SELECTION_REQUIRED", + "fallback", + "error.play.character-selection-required", + java.util.Map.of("playUsage", "PLAY demo "))); + + assertThat(rendered) + .isEqualTo( + "ERROR PLAY_SELECTION_REQUIRED Sélection requise. Utilisez PLAY demo " + + "avec le nom d’un personnage connu."); + } + @Test void localizedUnknownHelpTopicUsesConfiguredLocaleTemplate() { TextPlayerOutputRenderer renderer = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index a53872b893..0f6fc928eb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -158,6 +158,34 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { verify(scriptEventPublisher).publishRegionExitEvent(context, "logout:41:1:7001", "LOGOUT"); } + @Test + void recordDisconnectedTakeoverSuppressesExitAndRecordsPresenceBeforeRemoval() { + SessionContext context = + new SessionContext( + 41L, + 22L, + net.firedevops.firemud.test.AccountRuntimeStubServer.accountUuidForTestFixture(123L), + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-1021", + ""); + whenGameplayContextPresent(context); + + service.recordDisconnected(41L, AccountRecentPresenceDisposition.TAKEOVER); + + verify(scriptEventPublisher, never()) + .publishRegionExitEvent(Mockito.any(SessionContext.class), anyString(), anyString()); + verify(sessionRoutingNormalizationService, never()).resolveProjectedSessionContext("41"); + org.mockito.InOrder inOrder = + Mockito.inOrder(accountRecentPresenceService, gameplayPresenceService); + inOrder + .verify(accountRecentPresenceService) + .recordDisconnect(41L, AccountRecentPresenceDisposition.TAKEOVER); + inOrder.verify(gameplayPresenceService).removeBySessionId(41L); + } + @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 8eda087830..205d5acb55 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -8,18 +8,16 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; +import net.firedevops.firemud.tcpproxy.v1.PingRequest; +import net.firedevops.firemud.tcpproxy.v1.PingResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.MDC; import org.springframework.boot.test.system.CapturedOutput; @@ -28,499 +26,360 @@ @ExtendWith(OutputCaptureExtension.class) class TcpProxyServiceImplTest { @Test - void notifyDisconnectSavesSuspendedState() { + void validDisconnectHintIsAcknowledgedAfterReadOnlyInstanceValidation() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); GameInstance entity = buildEntity(12L, 7L); Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); - - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setGameInstanceId("12") - .setTenantId("7") - .build(), - new StreamObserver<>() { - @Override - public void onNext(NotifyDisconnectResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("OK", ref.get().getError().getCode()); - ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(GameInstanceDto.class); - Mockito.verify(sessionStateService).saveState(stateCaptor.capture()); - assertEquals("SUSPENDED", stateCaptor.getValue().status()); - assertEquals("patch", stateCaptor.getValue().scriptPatchVersion()); - assertEquals(3L, stateCaptor.getValue().scriptPinEpoch()); - assertEquals("pin-request-3", stateCaptor.getValue().scriptPinControlPlaneRequestId()); + MeterRegistry meterRegistry = new SimpleMeterRegistry(); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("41") + .setGameInstanceId("12") + .setTenantId("7") + .build()); + + assertEquals("OK", response.getError().getCode()); + assertEquals("Disconnect recorded", response.getError().getMessage()); + assertEntityUnchanged(entity); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); } @Test - void notifyDisconnectAddsGameplayLoggingContext() { + void notifyDisconnectRetainsGameplayLoggingContext() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); - GameInstance entity = buildEntity(12L, 7L); - Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); - Mockito.doAnswer( + Mockito.when(repository.findById(12L)) + .thenAnswer( ignored -> { assertEquals("7", MDC.get("tenantId")); assertEquals("12", MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); - return null; - }) - .when(sessionStateService) - .saveState(Mockito.any()); - + return Optional.of(buildEntity(12L, 7L)); + }); TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setGameInstanceId("12") - .setTenantId("7") - .build(), - observerFor(ref)); - - assertEquals("OK", ref.get().getError().getCode()); + service(repository, new SimpleMeterRegistry(), acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder().setGameInstanceId("12").setTenantId("7").build()); + + assertEquals("OK", response.getError().getCode()); assertEquals(null, MDC.get("tenantId")); assertEquals(null, MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); } @Test - void notifyDisconnectRejectsInvalidTenant(CapturedOutput output) { + void notifyDisconnectRejectsInvalidTenantWithoutInstanceLookup(CapturedOutput output) { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setGameInstanceId("12") - .setTenantId("bad") - .build(), - new StreamObserver<>() { - @Override - public void onNext(NotifyDisconnectResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be a number", ref.get().getError().getMessage()); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("12") + .setGameInstanceId("12") + .setTenantId("bad") + .build()); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("tenantId must be a number", response.getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); org.assertj.core.api.Assertions.assertThat(output) .contains( "NotifyDisconnect returned app error INVALID_ARGUMENT: tenantId must be a number"); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test - void notifyDisconnectRejectsZeroGameInstanceId() { + void notifyDisconnectRejectsNonPositiveInstanceId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setGameInstanceId("0") - .setTenantId("7") - .build(), - observerFor(ref)); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("gameInstanceId must be positive", ref.get().getError().getMessage()); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("12") + .setGameInstanceId("0") + .setTenantId("7") + .build()); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("gameInstanceId must be positive", response.getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test - void notifyDisconnectRejectsZeroTenantId() { + void notifyDisconnectRejectsNonPositiveTenantId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setGameInstanceId("12") - .setTenantId("0") - .build(), - observerFor(ref)); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("12") + .setGameInstanceId("12") + .setTenantId("0") + .build()); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("tenantId must be positive", response.getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test - void duplicateDisconnectHintsAreIgnoredAndMetered() { + void notifyDisconnectRejectsWrongTenantWithoutChangingInstance() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true, false); GameInstance entity = buildEntity(12L, 7L); Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); + MeterRegistry meterRegistry = new SimpleMeterRegistry(); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("41") + .setGameInstanceId("12") + .setTenantId("9") + .build()); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("Tenant does not own session", response.getError().getMessage()); + assertEntityUnchanged(entity); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); + } + @Test + void notifyDisconnectReturnsNotFoundForMissingInstance() { + GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); + Mockito.when(repository.findById(12L)).thenReturn(Optional.empty()); TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - NotifyDisconnectRequest request = - NotifyDisconnectRequest.newBuilder() - .setGameInstanceId("12") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(1L) - .build(); - - AtomicReference first = new AtomicReference<>(); - AtomicReference second = new AtomicReference<>(); - - service.notifyDisconnect(request, observerFor(first)); - service.notifyDisconnect(request, observerFor(second)); - - assertEquals("OK", first.get().getError().getCode()); - assertEquals("OK", second.get().getError().getCode()); - assertEquals( - 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); + service(repository, new SimpleMeterRegistry(), acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder().setGameInstanceId("12").setTenantId("7").build()); + + assertEquals("NOT_FOUND", response.getError().getCode()); + assertEquals("Game instance not found", response.getError().getMessage()); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); } @Test - void lateDisconnectHintsAreIgnoredAndMetered() { + void duplicateDisconnectHintIsAcknowledgedAndMeteredWithoutRepeatLookup() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = + GameInstance entity = buildEntity(12L, 7L); + Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); + DisconnectDeduplicationService deduplication = Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) + Mockito.when(deduplication.shouldProcess(Mockito.anyString(), Mockito.anyLong())) .thenReturn(true, false); + MeterRegistry meterRegistry = new SimpleMeterRegistry(); + TcpProxyServiceImpl service = service(repository, meterRegistry, deduplication); + NotifyDisconnectRequest request = sequencedHint(2L); + + NotifyDisconnectResponse first = notifyDisconnect(service, request); + NotifyDisconnectResponse duplicate = notifyDisconnect(service, request); + + assertEquals("OK", first.getError().getCode()); + assertEquals("OK", duplicate.getError().getCode()); + assertEquals("Duplicate disconnect ignored", duplicate.getError().getMessage()); + assertEquals( + 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); + assertEntityUnchanged(entity); + Mockito.verify(deduplication, Mockito.times(2)).shouldProcess("proxy-1", 2L); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void olderDisconnectSequenceIsIgnoredAndMetered() { + GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); GameInstance entity = buildEntity(12L, 7L); Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); + DisconnectDeduplicationService deduplication = + Mockito.mock(DisconnectDeduplicationService.class); + Mockito.when(deduplication.shouldProcess(Mockito.anyString(), Mockito.anyLong())) + .thenReturn(true, false); + MeterRegistry meterRegistry = new SimpleMeterRegistry(); + TcpProxyServiceImpl service = service(repository, meterRegistry, deduplication); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - NotifyDisconnectRequest firstRequest = - NotifyDisconnectRequest.newBuilder() - .setGameInstanceId("12") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(2L) - .build(); - NotifyDisconnectRequest lateRequest = - NotifyDisconnectRequest.newBuilder() - .setGameInstanceId("12") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(1L) - .build(); - - AtomicReference first = new AtomicReference<>(); - AtomicReference second = new AtomicReference<>(); - - service.notifyDisconnect(firstRequest, observerFor(first)); - service.notifyDisconnect(lateRequest, observerFor(second)); - - assertEquals("OK", first.get().getError().getCode()); - assertEquals("OK", second.get().getError().getCode()); + NotifyDisconnectResponse newest = notifyDisconnect(service, sequencedHint(2L)); + NotifyDisconnectResponse older = notifyDisconnect(service, sequencedHint(1L)); + + assertEquals("OK", newest.getError().getCode()); + assertEquals("OK", older.getError().getCode()); + assertEquals("Duplicate disconnect ignored", older.getError().getMessage()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); + assertEntityUnchanged(entity); + Mockito.verify(deduplication).shouldProcess("proxy-1", 2L); + Mockito.verify(deduplication).shouldProcess("proxy-1", 1L); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); } @Test - void disconnectWithoutBootstrapMetadataIsMetered() { + void acceptedHintAfterDedupeResetRemainsEffectFree() { + GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); + GameInstance entity = buildEntity(12L, 7L); + Mockito.when(repository.findById(12L)).thenReturn(Optional.of(entity)); + DisconnectDeduplicationService deduplication = acceptingDeduplication(); + TcpProxyServiceImpl service = service(repository, new SimpleMeterRegistry(), deduplication); + + // A missing/reset dedupe record may admit the hint; it still is not authority to mutate state. + NotifyDisconnectResponse response = notifyDisconnect(service, sequencedHint(3L)); + + assertEquals("OK", response.getError().getCode()); + assertEntityUnchanged(entity); + Mockito.verify(deduplication).shouldProcess("proxy-1", 3L); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void missingProxyMetadataWithOptionalSessionIdIsMeteredWithoutEffects() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect(NotifyDisconnectRequest.newBuilder().build(), observerFor(ref)); - - assertEquals("OK", ref.get().getError().getCode()); + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder().setSessionId("12").setTenantId("7").build()); + + assertEquals("OK", response.getError().getCode()); + assertEquals( + "Disconnect recorded (no proxy bootstrap metadata)", response.getError().getMessage()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(repository); } @Test - void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { + void missingProxyMetadataDoesNotInterpretSessionIdAsInstanceId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); - - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("12") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(1L) - .build(), - observerFor(ref)); - - assertEquals("OK", ref.get().getError().getCode()); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); + + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder() + .setSessionId("12") + .setTenantId("7") + .setProxyConnectionId("proxy-1") + .setDisconnectSequence(1L) + .build()); + + assertEquals("OK", response.getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verify(gameplayPresenceLifecycleService) - .recordDisconnected( - 12L, - net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition - .TRANSPORT_LOSS); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test - void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { + void invalidOptionalSessionIdDoesNotAffectMissingContextAcknowledgement() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = - Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) - .thenReturn(true); + TcpProxyServiceImpl service = service(repository, meterRegistry, acceptingDeduplication()); - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("0") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(1L) - .build(), - observerFor(ref)); - - assertEquals("OK", ref.get().getError().getCode()); + NotifyDisconnectResponse response = + notifyDisconnect( + service, + NotifyDisconnectRequest.newBuilder().setSessionId("-1").setTenantId("7").build()); + + assertEquals("OK", response.getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test - void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { + void pingStillDelegatesToPingService() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - DisconnectDeduplicationService disconnectDeduplicationService = + Mockito.when(pingService.ping()).thenReturn("pong"); + TcpProxyServiceImpl service = + new TcpProxyServiceImpl(repository, meterRegistry, pingService, acceptingDeduplication()); + AtomicReference responseRef = new AtomicReference<>(); + + service.ping( + PingRequest.getDefaultInstance(), + new StreamObserver<>() { + @Override + public void onNext(PingResponse value) { + responseRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("pong", responseRef.get().getMessage()); + Mockito.verify(pingService).ping(); + Mockito.verifyNoInteractions(repository); + } + + private static TcpProxyServiceImpl service( + GameInstanceRepository repository, + MeterRegistry meterRegistry, + DisconnectDeduplicationService deduplication) { + return new TcpProxyServiceImpl( + repository, meterRegistry, Mockito.mock(PingService.class), deduplication); + } + + private static DisconnectDeduplicationService acceptingDeduplication() { + DisconnectDeduplicationService deduplication = Mockito.mock(DisconnectDeduplicationService.class); - Mockito.when( - disconnectDeduplicationService.shouldProcess(Mockito.anyString(), Mockito.anyLong())) + Mockito.when(deduplication.shouldProcess(Mockito.anyString(), Mockito.anyLong())) .thenReturn(true); + return deduplication; + } - TcpProxyServiceImpl service = - new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); - - AtomicReference ref = new AtomicReference<>(); - service.notifyDisconnect( - NotifyDisconnectRequest.newBuilder() - .setSessionId("-1") - .setTenantId("7") - .setProxyConnectionId("proxy-1") - .setDisconnectSequence(1L) - .build(), - observerFor(ref)); - - assertEquals("OK", ref.get().getError().getCode()); - assertEquals( - 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); - Mockito.verifyNoInteractions(repository); + private static NotifyDisconnectRequest sequencedHint(long sequence) { + return NotifyDisconnectRequest.newBuilder() + .setSessionId("41") + .setGameInstanceId("12") + .setTenantId("7") + .setProxyConnectionId("proxy-1") + .setDisconnectSequence(sequence) + .build(); + } + + private static NotifyDisconnectResponse notifyDisconnect( + TcpProxyServiceImpl service, NotifyDisconnectRequest request) { + AtomicReference responseRef = new AtomicReference<>(); + service.notifyDisconnect(request, observerFor(responseRef)); + return responseRef.get(); } private static StreamObserver observerFor( @@ -541,9 +400,20 @@ public void onCompleted() {} }; } - private static GameInstance buildEntity(long sessionId, long tenantId) { + private static void assertEntityUnchanged(GameInstance entity) { + assertEquals(12L, entity.getId()); + assertEquals(7L, entity.getTenantId()); + assertEquals("rt", entity.getRuntimeVersion()); + assertEquals("patch", entity.getScriptPatchVersion()); + assertEquals(3L, entity.getScriptPinEpoch()); + assertEquals("pin-request-3", entity.getScriptPatchPinnedControlPlaneRequestId()); + assertEquals(99L, entity.getOwnerAccountId()); + assertEquals("RUNNING", entity.getStatus()); + } + + private static GameInstance buildEntity(long gameInstanceId, long tenantId) { GameInstance entity = new GameInstance(); - entity.setId(sessionId); + entity.setId(gameInstanceId); entity.setTenantId(tenantId); entity.setRuntimeVersion("rt"); entity.setScriptPatchVersion("patch"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 3457ff0cda..1841da985a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -28,6 +28,7 @@ import net.firedevops.firemud.gamesession.config.EffectiveSettingsResolver; import net.firedevops.firemud.gamesession.config.PresentationProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; +import net.firedevops.firemud.gamesession.presentation.LookViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.PromptBurstCoordinator; import net.firedevops.firemud.gamesession.presentation.PromptComposer; @@ -44,6 +45,9 @@ import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.web.socket.CloseStatus; @@ -994,6 +998,8 @@ void handleMessageForcesPromptBurstByUiActionMetadata() throws Exception { void handleMessageForcesPromptBurstForGameplayEntryMetadata() throws Exception { TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); PlayerOutput output = PlayerOutput.message("Entering Demo World"); + ScreenBufferService.BufferedEntry bufferedEntry = + ScreenBufferService.BufferedEntry.fromText("Entering Demo World\n"); SessionContext context = GameplayCommandTestFixtures.webSocketEmberline(); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) @@ -1014,13 +1020,23 @@ void handleMessageForcesPromptBurstForGameplayEntryMetadata() throws Exception { any(PresentationProperties.class), any())) .thenReturn("OK PLAY"); + when(outputProjector.renderClassicPlayerOutput( + eq(output), eq("en-NZ"), any(PresentationProperties.class))) + .thenReturn("Entering Demo World"); when(outputProjector.toBufferedEntry(any(PlayerOutput.class), any(String.class))) - .thenReturn(ScreenBufferService.BufferedEntry.fromText("Entering Demo World\n")); + .thenReturn(bufferedEntry); handler.handleMessage(session, new TextMessage("PLAY demo")); verify(promptBurstCoordinator) .applyPromptWindow(eq("41"), eq(context), eq(List.of(output)), eq(true)); + verify(screenBufferService) + .append( + context.tenantId(), + context.gameInstanceId(), + context.characterId(), + List.of(bufferedEntry)); + Mockito.verifyNoInteractions(lookHandler); } @Test @@ -1114,6 +1130,177 @@ void handleMessageKeepsNonUiCommunicationUnderNormalPromptBurstPolicy() throws E verify(session, never()).sendMessage(any(TextMessage.class)); } + @ParameterizedTest + @CsvSource({ + "true, true, true", "true, false, true", "false, true, true", "false, false, true", + "true, true, false", "true, false, false", "false, true, false", "false, false, false" + }) + void genericReconnectSkipsPrivateBufferAndAlwaysRedrawsWithEffectivePromptPolicy( + boolean enabled, boolean emitAfterRestore, boolean bufferAvailable) throws Exception { + SessionContext context = reconnectGameplayContext(); + PresentationProperties presentation = + new PresentationProperties( + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(enabled, emitAfterRestore, 150L)); + when(settingsResolver.presentation(context)).thenReturn(presentation); + when(screenBufferService.get(22L, 1L, 123L)) + .thenReturn( + bufferAvailable + ? Optional.of( + new ScreenBufferService.BufferedScreen( + List.of(ScreenBufferService.BufferedEntry.fromText("PRIVATE CONTEXT")), + 1, + 1, + 1L)) + : Optional.empty()); + prepareReconnectInterpretation(TextCommandType.PLAY, true, true, context); + PlayerOutput look = PlayerOutput.message("Fresh room\n"); + PlayerOutput prompt = PlayerOutput.prompt("HP: 10> "); + when(lookHandler.describePlayerOutput( + "41", true, LookViewOutput.RefreshReason.RECONNECT_REFRESH)) + .thenReturn(look); + when(outputProjector.projectPlayerOutput(session, look, "en-NZ", presentation)) + .thenReturn("Fresh room\n"); + when(promptComposer.compose(context)).thenReturn(Optional.of(prompt)); + when(outputProjector.projectPlayerOutput(session, prompt, "en-NZ", presentation)) + .thenReturn("HP: 10> "); + + handler.handleMessage(session, new TextMessage("PLAY")); + + verify(screenBufferService, never()) + .get(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + verify(lookHandler) + .describePlayerOutput("41", true, LookViewOutput.RefreshReason.RECONNECT_REFRESH); + int promptCount = enabled && emitAfterRestore ? 1 : 0; + verify(promptComposer, Mockito.times(promptCount)).compose(context); + verify(promptBurstCoordinator, Mockito.times(promptCount)).recordPromptEmission("41"); + ArgumentCaptor messages = ArgumentCaptor.forClass(TextMessage.class); + verify(session, Mockito.times(2 + promptCount)).sendMessage(messages.capture()); + assertThat(messages.getAllValues().stream().map(TextMessage::getPayload).toList()) + .containsExactlyElementsOf( + promptCount == 1 + ? List.of("OK PLAY\n", "Fresh room\n", "HP: 10> ") + : List.of("OK PLAY\n", "Fresh room\n")); + } + + @Test + void controlledAcceptedFirstPartyInterpretationRedrawsWithoutConnectContextOrRecommendation() + throws Exception { + // This isolates rendering only: no first-party LOGIN, admission, or bootstrap success is + // proved. + when(session.getId()).thenReturn("controlled-renderer-session"); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(session)); + SessionContext context = reconnectGameplayContext(); + prepareReconnectInterpretation(TextCommandType.PLAY, true, false, context); + PlayerOutput look = PlayerOutput.message("Fresh room\n"); + when(lookHandler.describePlayerOutput( + "41", true, LookViewOutput.RefreshReason.RECONNECT_REFRESH)) + .thenReturn(look); + when(outputProjector.projectPlayerOutput( + eq(session), eq(look), eq("en-NZ"), any(PresentationProperties.class))) + .thenReturn("Fresh room\n"); + + handler.handleMessage(session, new TextMessage("PLAY")); + + verify(lookHandler) + .describePlayerOutput("41", true, LookViewOutput.RefreshReason.RECONNECT_REFRESH); + verify(screenBufferService, never()) + .get(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + InOrder order = Mockito.inOrder(session); + order.verify(session).sendMessage(argThat(message -> "OK PLAY\n".equals(message.getPayload()))); + order + .verify(session) + .sendMessage(argThat(message -> "Fresh room\n".equals(message.getPayload()))); + order.verifyNoMoreInteractions(); + } + + @ParameterizedTest + @CsvSource({"PLAY, false, true", "LOGIN, true, true", "PLAY, true, false"}) + void genericConnectContextAloneAndUnacceptedOrNonPlayCommandsDoNotRestore( + TextCommandType type, boolean accepted, boolean redrawRecommended) throws Exception { + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, + "unqualified-context")); + prepareReconnectInterpretation(type, accepted, redrawRecommended, reconnectGameplayContext()); + + handler.handleMessage(session, new TextMessage(type.name())); + + verify(screenBufferService, never()) + .get(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions(lookHandler, promptComposer); + } + + @Test + void reconnectWithMissingGameplayContextDoesNotRestore() throws Exception { + prepareReconnectInterpretation(TextCommandType.PLAY, true, true, null); + + handler.handleMessage(session, new TextMessage("PLAY")); + + verify(screenBufferService, never()) + .get(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions(lookHandler, promptComposer); + } + + private SessionContext reconnectGameplayContext() { + return new SessionContext( + 41L, + 22L, + GameplayCommandTestFixtures.communicationSenderEmberline().accountId(), + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt", + "en-NZ", + 1L); + } + + private void prepareReconnectInterpretation( + TextCommandType type, boolean accepted, boolean redrawRecommended, SessionContext context) { + TextCommand command = new TextCommand(type, List.of(), type.name()); + when(parser.parse(type.name())).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + accepted + ? CommandEnqueueResult.success() + : CommandEnqueueResult.failure("PLAY_REQUIRED", "PLAY required"), + List.of(), + redrawRecommended, + false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.ofNullable(context)); + when(promptBurstCoordinator.applyPromptWindow(any(), any(), any(), anyBoolean())) + .thenReturn(List.of()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + Mockito.nullable(String.class), + any(PresentationProperties.class), + Mockito.nullable(SessionContext.class))) + .thenReturn(accepted ? "OK " + type.name() + "\n" : "ERROR PLAY_REQUIRED PLAY required\n"); + } + @Test void handleMessageDoesNotReplayReconnectBufferForNormalizedLoggedInShell() throws Exception { TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); @@ -1141,6 +1328,9 @@ void handleMessageDoesNotReplayReconnectBufferForNormalizedLoggedInShell() throw handler.handleMessage(session, new TextMessage("PLAY demo")); verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions(lookHandler, promptComposer); } @Test @@ -1172,6 +1362,9 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() handler.handleMessage(session, new TextMessage("PLAY demo")); verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); + verify(screenBufferService, never()) + .clear(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions(lookHandler, promptComposer); } @Test From 722c0c057f854d965c3154ce0a2fc88ab2d52ddd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:00:29 +1300 Subject: [PATCH 04/23] Format renamed reconnect refresh helper --- .../gamesession/websocket/GameSessionWebSocketHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 5b5fbe48f4..1ed52ed35d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -251,8 +251,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) outputs, resolveLocaleTag(session, sessionId), effectivePresentation); - maybeRefreshReconnectLook( - session, sessionId, command, interpretation, maybeContext); + maybeRefreshReconnectLook(session, sessionId, command, interpretation, maybeContext); maybeCloseAfterSuccessfulLogout(session, command, interpretation); } catch (SessionContextUnavailableException unavailable) { logger.warn( From 0c59abca98c3b1723217bcd4e3ed1d941dad7f8a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:09:10 +1300 Subject: [PATCH 05/23] Record local JVM crash and scoped validation recovery --- design/project-management/ai-observations.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2fc7a8e9e2..975dc5cca9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -26,3 +26,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Local executable mode loss and a later successful check masked certificate-contract failure. - During #3367 CLI4 qualification, `generate-dev-certs.sh` was tracked as `100755` but locally `0644` with `core.filemode=false`; `ensure-dev-certs.sh` therefore failed to execute it. The multi-command caller lacked failure propagation and returned the later documentation check’s success. Root inspected the failed contract log, restored only the generator’s tracked executable permission, and reran the contract and ShellCheck with explicit fail-fast propagation; both pass. The original failure remains retained in R1425 and was reported to Overseer. The mode-change cause is unproven; on recurrence, capture the affected file’s mode before and after the scoped mutation rather than changing unrelated worktrees. + +- `2026-11-01` (Pacific/Auckland): Local Gradle daemon crashed in G1 while its worker set retained the resource slot. + - R1424’s consolidated receiving gate at `722c0c057f85` crashed Temurin 21.0.10+7 daemon `3293351` with `SIGSEGV` in `G1RebuildRemSetClosure` at 11:02:31am NZDT. The Gradle client reported daemon disappearance, but the canonical supervisor still held the resource slot several minutes later. Root preserved the fatal log privately, then signalled only the verified outer wrapper through a pidfd; its owned workers drained and the waiting documentation gate passed. No unrelated daemon was touched. The JVM crash cause and delayed automatic drain are unproven; the consolidated proof remains incomplete pending a fresh invocation. The exact failure and recovery were reported to Overseer; retain marker/process evidence on a natural recurrence before changing the JVM or wrapper. From 97265b043a85e03645bebe64e0fe8f520fe37713 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:19:01 +1300 Subject: [PATCH 06/23] Keep takeover resumption proof free of false region exits --- .../command/text/SessionResumptionFlowTest.java | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 5f6118991d..bbb729a907 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -401,16 +401,8 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { verify(accountRecentPresenceService) .recordDisconnect(1L, AccountRecentPresenceDisposition.TAKEOVER); - verify(scriptEventPublisher) - .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:7001"), - Mockito.eq("TAKEOVER")); + verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); } From f427e71b128aec5479b6af93ec120ade6510da15 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:07:17 +1300 Subject: [PATCH 07/23] docs: retain receiving-proof recovery and CI network evidence --- design/project-management/ai-observations.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 975dc5cca9..2b77fc91b0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -29,3 +29,7 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Local Gradle daemon crashed in G1 while its worker set retained the resource slot. - R1424’s consolidated receiving gate at `722c0c057f85` crashed Temurin 21.0.10+7 daemon `3293351` with `SIGSEGV` in `G1RebuildRemSetClosure` at 11:02:31am NZDT. The Gradle client reported daemon disappearance, but the canonical supervisor still held the resource slot several minutes later. Root preserved the fatal log privately, then signalled only the verified outer wrapper through a pidfd; its owned workers drained and the waiting documentation gate passed. No unrelated daemon was touched. The JVM crash cause and delayed automatic drain are unproven; the consolidated proof remains incomplete pending a fresh invocation. The exact failure and recovery were reported to Overseer; retain marker/process evidence on a natural recurrence before changing the JVM or wrapper. + - Outcome at 12:05pm NZDT on 1 November: the replacement consolidated gate at `97265b043a85` passed its 966 selected cases with zero failures, errors or skips, enabled static checks, full formatting, packaging and documentation checks. The subsequent current-source, eleven-image held-admission smoke passed with authenticated teardown and independently empty project containers, networks and volumes. The JVM crash and delayed-drain causes remain unknown; successful replacement proof does not identify either cause. + +- `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. + - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. From 89782c734732d9d8e109cf65b7cd432001a3dd0c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:20:35 +1300 Subject: [PATCH 08/23] Bind catalog decisions to one snapshot and guard public pointer cardinality --- .../game-session-service/protocols.md | 4 +- .../game-session-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 3 + ...r-experience-commands-and-communication.md | 4 +- .../realm-routing-and-playable-state.md | 4 +- .../command/text/GameplayWorldCatalog.java | 148 +++++++-- .../command/text/PlayCommandHandler.java | 54 ++- .../command/text/WorldsCommandHandler.java | 5 +- .../service/impl/GameSessionGrpcService.java | 15 +- ...nforce_tenant_public_realm_cardinality.sql | 3 + ...sionPointerCardinalityIntegrationTest.java | 309 ++++++++++++++++++ .../DirectTextWorldSelectionServiceTest.java | 46 ++- .../text/GameplayWorldCatalogTest.java | 57 +++- .../command/text/PlayCommandHandlerTest.java | 52 +++ .../text/WorldsCommandHandlerTest.java | 18 + .../WorldsTextCommandDispatchHandlerTest.java | 24 ++ .../impl/GameSessionGrpcServiceTest.java | 107 +++++- 17 files changed, 750 insertions(+), 105 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1053__enforce_tenant_public_realm_cardinality.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 85c4c67e0f..f5323c8e74 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,6 +14,8 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Current catalog receiving remains partial. Fresh Game Session catalog reads reject numeric world and realm selectors instead of interpreting them as positions in the latest list. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. + Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). ### Reset and Recovery Consequence @@ -76,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current catalog-side world and realm resolution refuses numeric selectors because transport-local menu retention is not wired into these readers. ### JOIN Translation and Status diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 3d07d9824c..0b17b00c44 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -34,6 +34,8 @@ The sections below define the target-state runtime contract. Current implementat - **Direct-text WORLDS menu retention:** the manually composed menu store and one-key Redis script retain only the public `WORLDS` UI snapshot under the tenantless proxy-UUID family. The numeric transport session ID and the exact observed proxy UUID remain separate correlation values; neither an observed UUID nor Redis `ACL WHOAMI` establishes authenticated receiving custody or LOGIN/JOIN authority. Missing, expired, reset, or source-stale menu state requires a fresh `WORLDS` request and cannot recreate or clear authentication state. Production protected-connection binding, receiving-chain provenance and hidden rebind remain gaps; the source has no deployed ACL change. Focused component and physical Redis proof is recorded in the owning tracker, without establishing genuine receiving custody or registration. See [the Redis menu contract](../../system-architecture-redis.md#direct-text-worlds-ui-menu) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). +- **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while fresh numeric selectors and ambiguous private defaults are refused. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). + - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 2b77fc91b0..244853a7cd 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -33,3 +33,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Two different repository-network failures interrupted one unchanged CI image build. - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. + +- `2026-11-01` (Pacific/Auckland): CI watch masked a proven failure while another required gate was missing. + - The shared observer retained a failed required Smoke check for #3369 while another required Validation check was absent, but returned pending rather than waking for the failure. Root inspected the actual failed image-build log and reported the discrepancy to FireController Worker; the worker confirmed the precedence defect at 12:17pm NZDT and deployed correction `edc11a7b`, retaining the counts and source guards. Next: verify failure wakeup on a natural failed check; owner-focused proof is reported, but this lane has not yet observed the corrected natural failure wakeup. The pending state never supplied success. A separate Hosted wait exited locally cancelled before the provider finished; Root recovered the original operation without reposting. The owner trace could not identify the signal sender, so no server timeout or evidence loss is established. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 292799e7ef..e58f7a3057 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -21,7 +21,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and `REALMS` remain supported. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | +| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; reconciled-candidate and fresh runtime proof remain pending. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | @@ -52,7 +52,7 @@ This section records implementation and proof status only. The target command, p Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings remain bounded current behavior; R1424 qualifies the bounded HELP/PLAY and WebSocket containment while preserving those existing outcomes. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also refuses numeric selectors on fresh catalog reads and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings remain bounded current behavior; R1424 qualifies the bounded HELP/PLAY and WebSocket containment while preserving those existing outcomes. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 9628e8df1c..071176814a 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -51,6 +51,8 @@ The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer a `GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. It groups rows by `{tenantId, worldSlug, realmSlug}` and emits a visible catalog entry only for exactly one complete row in that tenant-qualified selector scope. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target; duplicate selector rows within a tenant, duplicate runtime matches, and incomplete rows disappear from player-facing catalog projection rather than selecting an arbitrary row. +The current local #2857 receiver correction keeps the catalog-side boundary fail-closed: numeric selectors are refused by fresh reads, and composed `PLAY`/`WORLDS` decisions use one immutable catalog snapshot. Public/caller-free realm snapshots contain only public-production realms, private-only defaults are not inferred when ambiguous, and `GetAdmissionPointer` validates the selected slug tuple against one actual tenant pointer-list response. This does not wire in the separate exact-target direct-text UUID menu store or establish complete canonical `tenantSlug/worldSlug` support; authenticated private `REALMS` retention, protected receiving, explicit `JOIN`, and first-party admission remain gaps. R1430 passes 293 selected command/catalog/gRPC unit cases and 11 actual PostgreSQL migration cases, with no failures, errors or skips, plus canonical jOOQ generation and enabled service static/format checks. The initial migration test compilation failure was corrected before the separate physical run; the retained unit result and successful migration result are distinct runs. `AA-3.1`/`AA-3.3` remain partial and `drift-found` because the complete target is still absent. V1053 adds only a forward partial unique guard for visible public-production pointer cardinality per tenant; zero remains physically representable and is rejected by current readers, while the current realm catalog and V12/V13 are unchanged. The two new PostgreSQL cases prove successful existing-data migration, unchanged retained rows/events and migration history, rejection of duplicate visible public-production rows, and atomic refusal for pre-existing duplicate authority; nine existing pointer-migration cases also pass. + Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, resolved `gameInstanceId`, and `pointerVersion` together, with `characterSelection` and `playableStateScope` where applicable. Partial, blank, non-positive, stale, or selector-inconsistent bundles are not authoritative. At ingress, proxy and remote control-plane callers must provide `worldSlug`, `realmSlug`, and `pointerVersion` together or none; partial `ScheduleRemoteFollowup` input and partial remote coordinator/followup/result filters return `INVALID_ARGUMENT` instead of widening to an unscoped query. Persisted/read-model partial bundles collapse to absent rather than being projected as current identity. @@ -97,7 +99,7 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. These are historical validation facts; the decision review did not rerun them. +The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. The bounded #2857 catalog/cardinality receiver has the focused R1430 proof above; a reconciled candidate and fresh source-built runtime qualification remain pending. These are historical validation facts; the decision review did not rerun them. ## Active Gaps diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 6bcea9e4e5..7f5cdd8e94 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -84,17 +84,38 @@ public Optional resolveWorld(String selector) { } private Optional resolveWorld(String selector, CatalogSnapshot snapshot) { - List visibleWorlds = visibleWorlds(snapshot); - List indexedWorlds = publicDiscoveryWorlds(snapshot); - try { - int index = Integer.parseInt(selector); - if (index >= 1 && index <= indexedWorlds.size()) { - return Optional.of(indexedWorlds.get(index - 1)); - } - } catch (NumberFormatException ignored) { - // Fall back to slug matching. + // A catalog read has no transport-local menu. Numeric input must be resolved by the + // retained selection owner, never against the ordering of a fresh catalog response. + return resolveWorldBySlug(selector, visibleWorlds(snapshot)); + } + + /** One immutable catalog read for the decisions composing a single command response. */ + public ReadSnapshot readSnapshot() { + return new ReadSnapshot(loadWorldSnapshot()); + } + + public final class ReadSnapshot { + private final CatalogSnapshot snapshot; + + private ReadSnapshot(CatalogSnapshot snapshot) { + this.snapshot = snapshot; + } + + public Optional resolveWorld(String selector) { + return selector == null || selector.isBlank() + ? Optional.empty() + : GameplayWorldCatalog.this.resolveWorld(selector, snapshot); + } + + public Optional resolveDefaultRealm(WorldView world) { + return GameplayWorldCatalog.this.resolveDefaultRealm(world, snapshot); + } + + public boolean hasValidPublicProductionRealm(long tenantId) { + return tenantId > 0L + && publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE; } - return resolveWorldBySlug(selector, visibleWorlds); } public Optional resolveWorldFromAuthoritySnapshot(String selector) { @@ -146,7 +167,10 @@ public Optional realmDiscoverySnapshot(WorldView selecte } WorldView currentWorld = selectedWorldMatches.getFirst(); - List currentVisibleRealms = visibleRealms(currentWorld); + // This read has no authenticated caller or grant evidence. Visibility alone must not + // disclose private/playtest realms through a public discovery snapshot. + List currentVisibleRealms = + visibleRealms(currentWorld).stream().filter(RealmView::publicProductionRealm).toList(); WorldView visibleWorld = new WorldView(currentWorld.slug(), currentWorld.displayName(), currentVisibleRealms); return Optional.of( @@ -163,22 +187,13 @@ public Optional resolvePublicWorldFromAuthoritySnapshot(String select } private Optional resolveWorld(String selector, List worlds) { - try { - int index = Integer.parseInt(selector); - if (index >= 1 && index <= worlds.size()) { - return Optional.of(worlds.get(index - 1)); - } - } catch (NumberFormatException ignored) { - // Fall back to slug matching. - } - List matches = - worlds.stream() - .filter(world -> selectorKey(selector).equals(selectorKey(world.slug()))) - .toList(); - return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); + return resolveWorldBySlug(selector, worlds); } private Optional resolveWorldBySlug(String selector, List worlds) { + if (isOrdinalSelector(selector)) { + return Optional.empty(); + } String normalized = selectorKey(selector); List matches = worlds.stream().filter(world -> normalized.equals(selectorKey(world.slug()))).toList(); @@ -186,7 +201,7 @@ private Optional resolveWorldBySlug(String selector, List } public Optional resolveRealm(WorldView world, String selector) { - if (world == null || selector == null || selector.isBlank()) { + if (world == null || selector == null || selector.isBlank() || isOrdinalSelector(selector)) { return Optional.empty(); } String normalized = selectorKey(selector); @@ -200,7 +215,11 @@ public Optional resolveRealm(WorldView world, String selector) { // Admission may resolve hidden realms, but callers must still perform membership and grant // checks. Optional resolveRealmForAdmission(WorldView world, String selector) { - if (world == null || selector == null || selector.isBlank() || world.realms() == null) { + if (world == null + || selector == null + || selector.isBlank() + || isOrdinalSelector(selector) + || world.realms() == null) { return Optional.empty(); } String normalized = selectorKey(selector); @@ -250,13 +269,14 @@ private Optional resolveDefaultRealm(WorldView world, CatalogSnapshot } // Non-public presentation remains available only when its tenant has an unambiguous public // production realm elsewhere in the catalog; zero or multiple public targets never default. - return visibleRealms.stream() - .map(RealmView::tenantId) - .distinct() - .allMatch( - tenantId -> - publicProductionRealmCardinality(snapshot, tenantId) - == PublicProductionRealmCardinality.EXACTLY_ONE) + return visibleRealms.size() == 1 + && visibleRealms.stream() + .map(RealmView::tenantId) + .distinct() + .allMatch( + tenantId -> + publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE) ? Optional.of(visibleRealms.getFirst()) : Optional.empty(); } @@ -400,6 +420,12 @@ public void requireUniqueVisiblePublicProductionRealm( } List pointers = loadAuthorityPointersForTenant(expectedPointer.tenantId()); + requireUniqueVisiblePublicProductionRealm(expectedPointer, pointers); + } + + private void requireUniqueVisiblePublicProductionRealm( + GameplayAdmissionPointerSnapshot expectedPointer, + List pointers) { if (!tenantHasValidPublicProductionAuthority(pointers, expectedPointer.tenantId())) { throw new AuthorityPointerUnavailableException( "Authoritative public-production realm is incomplete or ambiguous for tenant " @@ -440,6 +466,12 @@ public void requireHealthyVisiblePrivateRealm(GameplayAdmissionPointerSnapshot e } List pointers = loadAuthorityPointersForTenant(expectedPointer.tenantId()); + requireHealthyVisiblePrivateRealm(expectedPointer, pointers); + } + + private void requireHealthyVisiblePrivateRealm( + GameplayAdmissionPointerSnapshot expectedPointer, + List pointers) { if (!tenantHasValidPublicProductionAuthority(pointers, expectedPointer.tenantId())) { throw new AuthorityPointerUnavailableException( "Authoritative public-production realm is incomplete or ambiguous for tenant " @@ -460,6 +492,40 @@ public void requireHealthyVisiblePrivateRealm(GameplayAdmissionPointerSnapshot e requireCollisionSafeVisiblePointer(pointers, expectedPointer); } + /** + * Resolves and validates one pointer response from a single actual tenant-authority read. The + * selector is still the current slug-shaped internal API, not a transport menu index. + */ + public Optional findAdmissionPointerFromAuthoritySnapshot( + long tenantId, + String worldSlug, + String realmSlug, + List pointerSnapshot) { + List pointers = + validateAuthorityPointersForTenant(pointerSnapshot, tenantId); + List matches = + pointers.stream() + .filter(pointer -> Objects.equals(pointer.worldSlug(), worldSlug)) + .filter(pointer -> Objects.equals(pointer.realmSlug(), realmSlug)) + .toList(); + if (matches.size() > 1) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay realm selection is ambiguous"); + } + if (matches.isEmpty()) { + return Optional.empty(); + } + GameplayAdmissionPointerSnapshot selected = matches.getFirst(); + if (selected.visible()) { + if (selected.publicProductionRealm()) { + requireUniqueVisiblePublicProductionRealm(selected, pointers); + } else { + requireHealthyVisiblePrivateRealm(selected, pointers); + } + } + return Optional.of(selected); + } + private static void requireCollisionSafeVisiblePointer( List pointers, GameplayAdmissionPointerSnapshot expectedPointer) { @@ -478,8 +544,12 @@ private static void requireCollisionSafeVisiblePointer( } private List loadAuthorityPointersForTenant(long tenantId) { - List pointers = - tenantAuthorityPointerSupplier.apply(tenantId); + return validateAuthorityPointersForTenant( + tenantAuthorityPointerSupplier.apply(tenantId), tenantId); + } + + private static List validateAuthorityPointersForTenant( + List pointers, long tenantId) { if (pointers == null) { throw new AuthorityPointerUnavailableException( "Authoritative tenant gameplay pointer list is unavailable"); @@ -498,7 +568,7 @@ private List loadAuthorityPointersForTenant(lo "Authoritative tenant gameplay pointer is incomplete"); } } - return pointers; + return List.copyOf(pointers); } private List worldEntries(List worlds) { @@ -873,6 +943,12 @@ private static String selectorKey(String slug) { return slug.trim().toLowerCase(Locale.ROOT); } + static boolean isOrdinalSelector(String selector) { + return selector != null + && !selector.isBlank() + && selector.trim().chars().allMatch(character -> character >= '0' && character <= '9'); + } + private record RealmSelectorKey(long tenantId, String selector) {} private static RealmView copyRealmView(RealmView input) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 5c4608c5ce..0474bec4f0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -196,7 +196,9 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { SessionContext context = maybeContext.get(); try (GameplayLoggingContext baseContext = GameplayLoggingContext.open(Long.toString(context.tenantId()), null, null, null)) { - Optional maybeSelection = resolveSelection(playRequest); + GameplayWorldCatalog.ReadSnapshot catalogSnapshot = gameplayWorldCatalog.readSnapshot(); + Optional maybeSelection = + resolveSelection(playRequest, catalogSnapshot); if (maybeSelection.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, @@ -211,7 +213,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { ResolvedPlaySelection selection = maybeSelection.orElseThrow(); Optional maybeWorld = - gameplayWorldCatalog.resolveWorld(selection.worldSelector()); + catalogSnapshot.resolveWorld(selection.worldSelector()); if (maybeWorld.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, @@ -251,7 +253,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { selection.explicitRealmSelector() != null ? gameplayWorldCatalog.resolveRealmForAdmission( selectedWorld, selection.explicitRealmSelector()) - : selectDefaultRealm(selectedWorld); + : selectDefaultRealm(selectedWorld, catalogSnapshot); if (maybeRealm.isEmpty()) { return failure( GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, @@ -266,7 +268,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); - if (!gameplayWorldCatalog.hasValidPublicProductionRealm(selectedRealm.tenantId())) { + if (!catalogSnapshot.hasValidPublicProductionRealm(selectedRealm.tenantId())) { return admissionPointerUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); } @@ -321,7 +323,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { context.sessionId()); return new PlayCommandHandlingResult( CommandEnqueueResult.success(), - List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), characterName)), + List.of(successNotice(selectedWorld, selectedRealm, characterName)), true); } @@ -375,7 +377,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return new PlayCommandHandlingResult( CommandEnqueueResult.success(), - List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), characterName)), + List.of(successNotice(selectedWorld, selectedRealm, characterName)), resumedOrTookOver || freshEntryFallback); } } @@ -550,19 +552,19 @@ private boolean handleExistingBinding( return true; } - private String formatSuccessResponse(String world, String realm, String character) { - String suffix = StringUtils.hasText(character) ? " as " + character : ""; - return "Entered world: " + displaySelection(world, realm) + suffix; - } - - private PlayerOutput successNotice(String world, String realm, String character) { + private PlayerOutput successNotice( + GameplayWorldCatalog.WorldView world, + GameplayWorldCatalog.RealmView realm, + String character) { String characterSuffix = StringUtils.hasText(character) ? " as " + character : ""; + String displaySelection = + realm.publicProductionRealm() ? world.slug() : world.slug() + " (" + realm.slug() + ")"; return PlayerOutput.notice( - formatSuccessResponse(world, realm, character), + "Entered world: " + displaySelection + characterSuffix, "notice.world.entered", Map.of( - "worldName", world, - "realmName", realm == null ? "" : realm, + "worldName", world.slug(), + "realmName", realm.slug(), "characterSuffix", characterSuffix)); } @@ -1009,7 +1011,8 @@ private boolean maybeRecordFreshEntryFallback( } private Optional resolveSelection( - TextCommandPayload.PlayRequest playRequest) { + TextCommandPayload.PlayRequest playRequest, + GameplayWorldCatalog.ReadSnapshot catalogSnapshot) { String worldSelector = playRequest.worldSelector(); if (!StringUtils.hasText(worldSelector)) { return Optional.empty(); @@ -1028,7 +1031,7 @@ private Optional resolveSelection( } Optional maybeWorld = - gameplayWorldCatalog.resolveWorld(worldSelector); + catalogSnapshot.resolveWorld(worldSelector); if (maybeWorld.isPresent() && StringUtils.hasText(secondSelector) && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { @@ -1038,11 +1041,12 @@ private Optional resolveSelection( } private Optional selectDefaultRealm( - GameplayWorldCatalog.WorldView selectedWorld) { + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.ReadSnapshot catalogSnapshot) { if (gameplayWorldCatalog.requiresExplicitRealmSelection(selectedWorld)) { return Optional.empty(); } - return gameplayWorldCatalog.resolveDefaultRealm(selectedWorld); + return catalogSnapshot.resolveDefaultRealm(selectedWorld); } private String explicitRealmSelectionMessage(GameplayWorldCatalog.WorldView selectedWorld) { @@ -1079,18 +1083,6 @@ private PlayCommandHandlingResult characterSelectionRequiredFailure( null); } - private String displaySelection(String world, String realm) { - if (!StringUtils.hasText(realm) - || gameplayWorldCatalog - .resolveWorld(world) - .flatMap(selectedWorld -> gameplayWorldCatalog.resolveRealm(selectedWorld, realm)) - .map(GameplayWorldCatalog.RealmView::publicProductionRealm) - .orElse(false)) { - return world; - } - return world + " (" + realm + ")"; - } - private String playUsage( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { return "PLAY " diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 66f5dd227d..702b7128be 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -35,8 +35,9 @@ public CharacterBrowseResult browseCharacters( if (!sessionContext.hasAccountIdentity()) { return CharacterBrowseResult.unavailable(); } + GameplayWorldCatalog.ReadSnapshot snapshot = worldCatalog.readSnapshot(); java.util.Optional maybeWorld = - worldCatalog.resolveWorld(worldSelector); + snapshot.resolveWorld(worldSelector); if (maybeWorld.isEmpty()) { return CharacterBrowseResult.invalidWorld(); } @@ -46,7 +47,7 @@ public CharacterBrowseResult browseCharacters( ? worldCatalog.resolveRealm(world, realmSelector) : worldCatalog.requiresExplicitRealmSelection(world) ? java.util.Optional.empty() - : worldCatalog.resolveDefaultRealm(world); + : snapshot.resolveDefaultRealm(world); if (StringUtils.hasText(realmSelector) && maybeRealm.isEmpty()) { return CharacterBrowseResult.invalidRealm(world.slug()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 544602d8d1..2987f6e290 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -757,16 +757,13 @@ public void getAdmissionPointer( long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); GameplayAdmissionPointerSnapshot realm = - gameplayAdmissionPointerAuthorityService - .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) + gameplayWorldCatalog + .findAdmissionPointerFromAuthoritySnapshot( + tenantId, + request.getWorldSlug(), + request.getRealmSlug(), + gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId)) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); - if (realm.visible()) { - if (realm.publicProductionRealm()) { - gameplayWorldCatalog.requireUniqueVisiblePublicProductionRealm(realm); - } else { - gameplayWorldCatalog.requireHealthyVisiblePrivateRealm(realm); - } - } GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() .setAdmissionPointer( diff --git a/services/game-session-service/src/main/resources/db/migration/V1053__enforce_tenant_public_realm_cardinality.sql b/services/game-session-service/src/main/resources/db/migration/V1053__enforce_tenant_public_realm_cardinality.sql new file mode 100644 index 0000000000..76d7a6d8b2 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1053__enforce_tenant_public_realm_cardinality.sql @@ -0,0 +1,3 @@ +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_tenant_visible_public_production + ON gameplay_admission_pointer (tenant_id) + WHERE visible = true AND public_production_realm = true; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java new file mode 100644 index 0000000000..3482c6ccde --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -0,0 +1,309 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameplayAdmissionPointerCardinalityIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + PathHolder.MIGRATIONS.toAbsolutePath().normalize(); + private static final String INDEX_NAME = + "uq_gameplay_admission_pointer_tenant_visible_public_production"; + private static final long ZERO_PUBLIC_TENANT_ID = 51001L; + private static final long SINGLE_PUBLIC_TENANT_ID = 51002L; + private static final long MULTIPLE_PUBLIC_TENANT_ID = 51003L; + private static final long OTHER_TENANT_ID = 51004L; + private static final long SINGLE_PUBLIC_ID = 5100201L; + private static final long VISIBLE_NONPUBLIC_ID = 5100203L; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String isolatedSchemaName; + + @AfterEach + void dropIsolatedSchema() { + if (isolatedSchemaName != null) { + DSL.using(dataSource(), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS " + isolatedSchemaName + " CASCADE"); + } + } + + @Test + void forwardIndexPreservesRetainedRowsAndEnforcesVisiblePublicCardinality() { + DriverManagerDataSource dataSource = isolatedDataSource(); + seedRetainedPointerHistory(dataSource, false); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + List retainedPointers = retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); + List retainedEvents = retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); + + migrateToVersion(dataSource, "1053"); + + assertThat(indexExists(dsl)).isTrue(); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")).isEqualTo(retainedPointers); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) + .isEqualTo(retainedEvents); + assertThat(visiblePublicCount(dsl, ZERO_PUBLIC_TENANT_ID)).isZero(); + assertThat(visiblePublicCount(dsl, SINGLE_PUBLIC_TENANT_ID)).isEqualTo(1L); + assertThat(visiblePublicCount(dsl, OTHER_TENANT_ID)).isEqualTo(1L); + assertThat( + scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE tenant_id = ? " + + "AND visible = false AND public_production_realm = true", + SINGLE_PUBLIC_TENANT_ID)) + .isEqualTo(1L); + assertThat( + scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE tenant_id = ? " + + "AND visible = true AND public_production_realm = false", + SINGLE_PUBLIC_TENANT_ID)) + .isEqualTo(1L); + assertThat( + scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE world_slug = 'one-main' " + + "AND realm_slug = 'production' AND visible = true " + + "AND public_production_realm = true")) + .isEqualTo(2L); + + assertUniqueIndexViolation( + () -> + dsl.execute( + "INSERT INTO gameplay_admission_pointer (world_slug, world_display_name, " + + "realm_slug, realm_display_name, tenant_id, game_instance_id, " + + "pointer_version, visible, requires_character_selection, state_scope, " + + "character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm) VALUES ('write-attempt', 'Write Attempt', " + + "'production', 'Production', ?, 9510201, 1, true, false, 'SHARED', " + + "'ALLOW_NEW', 'test/cardinality', 'second public insert', true)", + SINGLE_PUBLIC_TENANT_ID)); + assertThat( + scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE tenant_id = ? " + + "AND world_slug = 'write-attempt'", + SINGLE_PUBLIC_TENANT_ID)) + .isZero(); + + String nonpublicBefore = rowAndXmin(dsl, VISIBLE_NONPUBLIC_ID); + assertUniqueIndexViolation( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET public_production_realm = true " + + "WHERE id = ?", + VISIBLE_NONPUBLIC_ID)); + assertThat(rowAndXmin(dsl, VISIBLE_NONPUBLIC_ID)).isEqualTo(nonpublicBefore); + assertThat(visiblePublicCount(dsl, SINGLE_PUBLIC_TENANT_ID)).isEqualTo(1L); + + List historyBeforeRerun = flywayHistory(dsl); + migrateToVersion(dataSource, "1053"); + assertThat(flywayHistory(dsl)).isEqualTo(historyBeforeRerun); + + DSLContext recreatedReaderDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DatabaseGameplayAdmissionPointerAuthorityService recreatedReader = + new DatabaseGameplayAdmissionPointerAuthorityService( + new GameplayAdmissionPointerRepository(recreatedReaderDsl), + new GameplayAdmissionPointerEventRepository(recreatedReaderDsl)); + assertThat(recreatedReader.findPointer(SINGLE_PUBLIC_TENANT_ID, "one-main", "production")) + .isPresent(); + } + + @Test + void duplicateRetainedRowsRefuseMigrationWithoutChangingDataOrHistory() { + DriverManagerDataSource dataSource = isolatedDataSource(); + seedRetainedPointerHistory(dataSource, true); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + List retainedPointers = retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); + List retainedEvents = retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); + List migrationHistory = flywayHistory(dsl); + + assertThat(visiblePublicCount(dsl, ZERO_PUBLIC_TENANT_ID)).isZero(); + assertThat(visiblePublicCount(dsl, SINGLE_PUBLIC_TENANT_ID)).isEqualTo(1L); + assertThat(visiblePublicCount(dsl, MULTIPLE_PUBLIC_TENANT_ID)).isEqualTo(2L); + assertThat(indexExists(dsl)).isFalse(); + + assertThatThrownBy(() -> migrateToVersion(dataSource, "1053")) + .satisfies(failure -> assertThat(rootCause(failure).getMessage()).contains(INDEX_NAME)); + + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")).isEqualTo(retainedPointers); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) + .isEqualTo(retainedEvents); + assertThat(flywayHistory(dsl)).isEqualTo(migrationHistory); + assertThat(indexExists(dsl)).isFalse(); + } + + private static void seedRetainedPointerHistory( + DriverManagerDataSource dataSource, boolean includeDuplicatePublicRows) { + migrateToVersion(dataSource, "5"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + List pointers = + List.of( + new RetainedPointer(5100101L, ZERO_PUBLIC_TENANT_ID, "zero-main", true, false), + new RetainedPointer(5100102L, ZERO_PUBLIC_TENANT_ID, "zero-hidden", false, true), + new RetainedPointer(5100201L, SINGLE_PUBLIC_TENANT_ID, "one-main", true, true), + new RetainedPointer(5100202L, SINGLE_PUBLIC_TENANT_ID, "one-hidden", false, true), + new RetainedPointer(5100203L, SINGLE_PUBLIC_TENANT_ID, "one-preview", true, false), + new RetainedPointer(5100401L, OTHER_TENANT_ID, "one-main", true, true)); + pointers.forEach(pointer -> insertRetainedPointer(dsl, pointer)); + if (includeDuplicatePublicRows) { + insertRetainedPointer( + dsl, new RetainedPointer(5100301L, MULTIPLE_PUBLIC_TENANT_ID, "multi-one", true, true)); + insertRetainedPointer( + dsl, new RetainedPointer(5100302L, MULTIPLE_PUBLIC_TENANT_ID, "multi-two", true, true)); + } + + migrateToVersion(dataSource, "6"); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (world_slug, realm_slug, " + + "world_display_name, realm_display_name, tenant_id, game_instance_id, " + + "pointer_version, visible, requires_character_selection, state_scope, " + + "character_creation_policy, actor_principal, reason, control_plane_request_id, " + + "occurred_at, prepared_version_upgrade_id, public_production_realm) " + + "SELECT pointer.world_slug, pointer.realm_slug, pointer.world_display_name, " + + "pointer.realm_display_name, pointer.tenant_id, pointer.game_instance_id, " + + "pointer.pointer_version, pointer.visible, pointer.requires_character_selection, " + + "pointer.state_scope, pointer.character_creation_policy, 'retained/test', " + + "'Pre-cardinality retained audit event', 'retained-cardinality:' || pointer.id, " + + "CURRENT_TIMESTAMP, NULL, pointer.public_production_realm " + + "FROM gameplay_admission_pointer pointer"); + migrateToVersion(dataSource, "7"); + migrateToVersion(dataSource, "8"); + migrateToVersion(dataSource, "1052"); + } + + private static void insertRetainedPointer(DSLContext dsl, RetainedPointer pointer) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, " + + "realm_slug, realm_display_name, tenant_id, game_instance_id, pointer_version, " + + "visible, requires_character_selection, state_scope, character_creation_policy, " + + "last_updated_by, last_update_reason, public_production_realm) " + + "VALUES (?, ?, ?, 'production', 'Production', ?, ?, 1, ?, false, 'SHARED', " + + "'ALLOW_NEW', 'retained/test', 'Pre-cardinality retained pointer', ?)", + pointer.id(), + pointer.worldSlug(), + "World " + pointer.worldSlug(), + pointer.tenantId(), + pointer.id(), + pointer.visible(), + pointer.publicProduction()); + } + + private DriverManagerDataSource isolatedDataSource() { + isolatedSchemaName = "pointer_cardinality_" + UUID.randomUUID().toString().replace("-", ""); + DSL.using(dataSource(), SQLDialect.POSTGRES).execute("CREATE SCHEMA " + isolatedSchemaName); + + DriverManagerDataSource isolated = dataSource(); + String separator = postgres.getJdbcUrl().contains("?") ? "&" : "?"; + isolated.setUrl( + postgres.getJdbcUrl() + separator + "currentSchema=" + isolatedSchemaName + ",public"); + return isolated; + } + + private static Flyway migrateToVersion(DriverManagerDataSource dataSource, String version) { + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion(version)) + .load(); + flyway.migrate(); + return flyway; + } + + private static List retainedRowsAndXmins(DSLContext dsl, String tableName) { + return dsl.fetch( + "SELECT id::text || ':' || xmin::text || ':' || " + + "encode(convert_to(to_jsonb(retained_row)::text, 'UTF8'), 'hex') " + + "FROM " + + tableName + + " AS retained_row ORDER BY id") + .getValues(0, String.class); + } + + private static String rowAndXmin(DSLContext dsl, long pointerId) { + return dsl.fetchOne( + "SELECT xmin::text || ':' || " + + "encode(convert_to(to_jsonb(pointer)::text, 'UTF8'), 'hex') " + + "FROM gameplay_admission_pointer AS pointer WHERE id = ?", + pointerId) + .get(0, String.class); + } + + private static List flywayHistory(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text FROM flyway_schema_history AS history_row " + + "ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static boolean indexExists(DSLContext dsl) { + return scalarLong( + dsl, + "SELECT COUNT(*) FROM pg_indexes WHERE schemaname = current_schema() " + + "AND indexname = ?", + INDEX_NAME) + == 1L; + } + + private static long visiblePublicCount(DSLContext dsl, long tenantId) { + return scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE tenant_id = ? " + + "AND visible = true AND public_production_realm = true", + tenantId); + } + + private static long scalarLong(DSLContext dsl, String query, Object... bindings) { + return dsl.fetchOne(query, bindings).get(0, Long.class); + } + + private static void assertUniqueIndexViolation(Runnable statement) { + assertThatThrownBy(statement::run) + .satisfies(failure -> assertThat(rootCause(failure).getMessage()).contains(INDEX_NAME)); + } + + private static Throwable rootCause(Throwable throwable) { + Throwable cause = throwable; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private record RetainedPointer( + long id, long tenantId, String worldSlug, boolean visible, boolean publicProduction) {} + + private static final class PathHolder { + private static final java.nio.file.Path MIGRATIONS = + java.nio.file.Path.of("src/main/resources/db/migration"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index a70422e074..161be52017 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -402,6 +402,46 @@ void invalidSelectorsDoNotReadSources(String selector) { verifyNoInteractions(reader); } + @Test + void bareTenantSelectionNeverFallsBackToAnotherTenantsWorldSlug() { + var first = target(""); + var tenantNamedLikeFirstWorld = target("tenant-world-collision"); + var service = + service( + List.of(world(first), world(tenantNamedLikeFirstWorld)), + List.of(first, tenantNamedLikeFirstWorld)); + var menu = service.browse().orElseThrow(); + + assertThat(menu.selectors()).containsExactly("studio/forest", "forest/other-world"); + assertThat(service.resolve(menu, "forest")).containsSame(tenantNamedLikeFirstWorld); + assertThat(service.resolve(menu, "studio/forest")).containsSame(first); + assertThat(service.resolve(menu, "forest/other-world")).containsSame(tenantNamedLikeFirstWorld); + assertThat(service.resolve(menu, "other-world")).isEmpty(); + } + + @Test + void retainedOrdinalCannotBeSilentlyUpgradedToANewCatalogRevision() { + var original = target(""); + var revised = target("revision"); + AtomicReference> worlds = new AtomicReference<>(List.of(world(original))); + var service = service(GameplayWorldCatalog.forWorldSupplier(worlds::get), List.of(original)); + var oldMenu = service.browse().orElseThrow(); + worlds.set(List.of(world(revised))); + when(reader.readCurrentTarget(original)).thenReturn(revised); + when(reader.readCurrentTarget(revised)).thenReturn(revised); + when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(revised)); + + assertThat(service.resolve(oldMenu, "1")).isEmpty(); + assertThat(oldMenu.worlds().getFirst().realms().getFirst().catalogRevision()).isEqualTo(1L); + var refreshed = service.browse().orElseThrow(); + assertThat(service.resolve(refreshed, "1")).containsSame(revised); + clock.now = NOW.plusSeconds(300); + clearInvocations(reader); + assertThat(service.resolve(oldMenu, "1")).isEmpty(); + assertThat(service.resolve(refreshed, "1")).isEmpty(); + verifyNoInteractions(reader); + } + @Test void reorderedCatalogNeverReinterpretsAnOldOrdinal() { var first = target(""); @@ -804,11 +844,15 @@ private static GameplayAdmissionPointerSnapshot pointer( /** Controlled owner evidence uses real record invariants, never numeric-to-UUID derivation. */ private static CanonicalPlayableTarget target(String change) { - boolean second = "second".equals(change) || "same-tenant".equals(change); + boolean second = + "second".equals(change) + || "same-tenant".equals(change) + || "tenant-world-collision".equals(change); boolean otherWorld = second || "duplicate-runtime".equals(change); String tenantSlug = switch (change) { case "second", "duplicate-runtime", "duplicate-world", "tenant-slug" -> "other-tenant"; + case "tenant-world-collision" -> "forest"; case "uppercase-tenant" -> "STUDIO"; case "bad-tenant" -> "bad/tenant"; default -> "studio"; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index fb5045a87f..145c97031d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -863,7 +863,7 @@ void discoverySnapshotReadsItsSourceOnce() { } @Test - void realmDiscoverySnapshotReadsOneCurrentSourceForTheExactSelectedWorld() { + void callerFreeRealmDiscoveryReadsOnceAndDoesNotExposePrivateOrHiddenRealms() { AtomicInteger supplierCalls = new AtomicInteger(); GameplayWorldCatalog.WorldView selectedWorld = new GameplayWorldCatalog.WorldView( @@ -889,10 +889,10 @@ void realmDiscoverySnapshotReadsOneCurrentSourceForTheExactSelectedWorld() { assertThat(realms.world().slug()).isEqualTo(discovery.worlds().getFirst().slug()); assertThat(realms.realms()) .extracting(GameplayWorldCatalog.RealmView::slug) - .containsExactly("live", "preview"); + .containsExactly("live"); assertThat(realms.world().realms()) .extracting(GameplayWorldCatalog.RealmView::slug) - .containsExactly("live", "preview"); + .containsExactly("live"); assertThat(realms.realms().getFirst()) .isEqualTo(discovery.worlds().getFirst().realms().getFirst()); assertThat(realms.fingerprint()).isEqualTo(discovery.fingerprint()); @@ -1122,7 +1122,7 @@ void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { } @Test - void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { + void numericWorldSelectionRequiresARetainedTransportMenuRatherThanAFreshCatalog() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -1133,10 +1133,57 @@ void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { .extracting( net.firedevops.firemud.gamesession.presentation.WorldsViewOutput.WorldEntry::slug) .containsExactly("demo"); - assertThat(catalog.resolveWorld("1").orElseThrow().slug()).isEqualTo("demo"); + assertThat(catalog.resolveWorld("1")).isEmpty(); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("1")).isEmpty(); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("1")).isEmpty(); + assertThat(catalog.browseRealms("1")).isEmpty(); assertThat(catalog.resolveWorld("invalid")).isPresent(); } + @Test + void commandReadSnapshotUsesOneActualPointerListForSelectionDefaultAndCardinality() { + GameplayAdmissionPointerSnapshot original = publicPointer("demo", "Demo World", 7L, 11L); + when(authorityService.listPointers()).thenReturn(List.of(original), List.of()); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + GameplayWorldCatalog.ReadSnapshot snapshot = catalog.readSnapshot(); + GameplayWorldCatalog.WorldView world = snapshot.resolveWorld("demo").orElseThrow(); + + assertThat(snapshot.resolveDefaultRealm(world)).contains(world.realms().getFirst()); + assertThat(snapshot.hasValidPublicProductionRealm(7L)).isTrue(); + assertThat(snapshot.resolveWorld("demo")).contains(world); + verify(authorityService).listPointers(); + verify(authorityService, never()).listPointersByTenant(Mockito.anyLong()); + assertThat(catalog.readSnapshot().resolveWorld("demo")).isEmpty(); + } + + @Test + void unboundNumericRealmSelectorsCannotBecomeRealmSlugs() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews(List.of(worldWithRealm("demo", "1", 7L, true))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); + + assertThat(catalog.resolveRealm(world, "1")).isEmpty(); + assertThat(catalog.resolveRealmForAdmission(world, "1")).isEmpty(); + } + + @Test + void defaultRealmNeverChoosesTheFirstOfSeveralPrivateRealms() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("production-world", "live", 7L, true), + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + realmView("alpha", "Alpha", 7L, 12L, 1L, true, false, "ALLOW_NEW"), + realmView("beta", "Beta", 7L, 13L, 1L, true, false, "ALLOW_NEW"))))); + + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("private-world").orElseThrow())) + .isEmpty(); + } + private static GameplayWorldCatalog.RealmView realmView( String realmSlug, String realmDisplayName, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 828ea7b3e0..af8a5ae8f9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -10,6 +10,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; @@ -171,6 +172,57 @@ void setUp() { }); } + @Test + void playComposesSelectionCardinalityAndSuccessFromOneActualPointerList() { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + var pointer = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.fromString("8845d6f0-e260-4ca2-99d7-8ced4387f96b"), + UUID.fromString("6c4da6d7-b29d-4a67-a465-b78007868653")); + when(authority.listPointers()).thenReturn(List.of(pointer), List.of()); + var localHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authority), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + + var result = localHandler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); + verify(authority).listPointers(); + verify(authority, never()).listPointersByTenant(Mockito.anyLong()); + verify(authority, never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + @Test void playPromotesSessionIntoGameplay() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index d0ae7b8153..e224892db3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -85,6 +86,23 @@ void browseCharactersFailsClosedAfterValidWorldAndDefaultRealmResolution() { .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); } + @Test + void charsRefusalComposesWorldAndDefaultRealmFromOneSnapshot() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + var original = + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties).visibleWorlds(); + AtomicInteger reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> reads.getAndIncrement() == 0 ? original : List.of()); + + assertThat( + new WorldsCommandHandler(catalog) + .browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + assertThat(reads).hasValue(1); + } + @Test void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { GameplayCatalogProperties.World demo = world("demo", 22L, 1L, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 74b89b5522..d811bf9af7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -49,6 +49,30 @@ void preparedJoinExplicitlyRefusesWithoutDiscoveryOrGameplayEffects() { Mockito.verifyNoInteractions(scriptEventPublisher); } + @Test + void unboundWorldOrdinalReturnsRediscoveryGuidanceWithoutPublishingAnEvent() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); + var result = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + new TextCommandParser().parse("REALMS 1"), + false, + Optional.of(GameplayCommandTestFixtures.authoredDispatchEmberline()), + Optional.empty())); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> + assertThat(output.text()) + .isEqualTo( + "ERROR INVALID_ARGUMENT REALMS requires a valid world selector. Use WORLDS first.")); + Mockito.verifyNoInteractions(scriptEventPublisher); + } + @Test void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = GameplayCommandTestFixtures.authoredDispatchEmberline(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index cfc54dac80..d5e0d2e6c0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -746,14 +746,96 @@ void gameplayDiscoverySuppressesTenantWithPublicRealmsAcrossDifferentWorlds() { Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); } + @Test + void admissionPointerResponseUsesOneTenantListForBothPublicAndPrivateTargets() { + for (boolean publicProduction : List.of(true, false)) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + var selected = authorityPointer("demo", "selected", 7L, 44L, true, publicProduction); + var original = + publicProduction + ? List.of(selected) + : List.of(selected, authorityPointer("live-world", "live", 7L, 55L, true, true)); + // A second read would observe a different target and different catalog cardinality. + Mockito.when(authority.listPointersByTenant(7L)) + .thenReturn( + original, List.of(authorityPointer("demo", "selected", 7L, 99L, true, false))); + var service = catalogService(authority); + + var response = admissionPointer(service, "demo", "selected"); + + assertFalse(response.hasError()); + assertEquals("44", response.getAdmissionPointer().getGameInstanceId()); + assertEquals(selected.pointerVersion(), response.getAdmissionPointer().getPointerVersion()); + assertEquals(selected.catalogRevision(), response.getAdmissionPointer().getCatalogRevision()); + assertEquals(selected.realmId().toString(), response.getAdmissionPointer().getRealmId()); + assertEquals( + selected.playableStateNamespaceId().toString(), + response.getAdmissionPointer().getPlayableStateNamespaceId()); + assertEquals(publicProduction, response.getAdmissionPointer().getPublicProductionRealm()); + Mockito.verify(authority).listPointersByTenant(7L); + Mockito.verify(authority, Mockito.never()).listPointers(); + Mockito.verify(authority, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + } + + @Test + void invalidFirstTenantSnapshotCannotBeReplacedByALaterHealthyRead() { + var selected = authorityPointer("demo", "selected", 7L, 44L, true, true); + List> invalidSnapshots = + List.of( + List.of(selected, selected), + List.of(selected, authorityPointer("other", "live", 7L, 55L, true, true)), + List.of(authorityPointer("demo", "selected", 7L, 44L, true, false)), + List.of(selected, authorityPointer("other", "live", 8L, 55L, true, true)), + java.util.Arrays.asList(selected, null)); + for (var invalid : invalidSnapshots) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authority.listPointersByTenant(7L)).thenReturn(invalid, List.of(selected)); + + var response = admissionPointer(catalogService(authority), "demo", "selected"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(authority).listPointersByTenant(7L); + Mockito.verify(authority, Mockito.never()).listPointers(); + Mockito.verify(authority, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + } + + private static GetAdmissionPointerResponse admissionPointer( + GameSessionGrpcService service, String worldSlug, String realmSlug) { + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + @Test void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot selectedPublicRealm = authorityPointer("alpha", "live", 7L, 44L, true, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "alpha", "live")) - .thenReturn(java.util.Optional.of(selectedPublicRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of(selectedPublicRealm, authorityPointer("beta", "live", 7L, 55L, true, true))); @@ -795,8 +877,6 @@ void getAdmissionPointerRejectsFoldedVisiblePrivateRealmAlias() { authorityPointer("demo", "live", 7L, 44L, true, true); GameplayAdmissionPointerSnapshot privateAlias = authorityPointer("demo", "LIVE", 7L, 45L, true, false); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "live")) - .thenReturn(java.util.Optional.of(publicRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(publicRealm, privateAlias)); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -836,8 +916,6 @@ void privateAdmissionRequiresAndUsesHealthyTenantCatalog() { authorityPointer("private", "preview", 7L, 66L, true, false); GameplayAdmissionPointerSnapshot publicRealm = authorityPointer("demo", "live", 7L, 44L, true, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) - .thenReturn(java.util.Optional.of(privateRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(privateRealm, publicRealm)); Mockito.when(pointerAuthorityService.listPointers()) @@ -878,8 +956,7 @@ void getAdmissionPointerReturnsHiddenMetadataWithoutPublicCardinalityAuthorizati Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot hiddenRealm = authorityPointer("private", "preview", 7L, 66L, false, true); - Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) - .thenReturn(java.util.Optional.of(hiddenRealm)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)).thenReturn(List.of(hiddenRealm)); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); @@ -914,7 +991,8 @@ public void onCompleted() {} assertEquals( hiddenRealm.playableStateNamespaceId().toString(), response.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).findPointer(7L, "private", "preview"); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).findPointer(7L, "private", "preview"); Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); } @@ -950,8 +1028,6 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(authoritativeSnapshot)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -1024,7 +1100,8 @@ public void onCompleted() {} assertEquals( "2ea958e0-13a2-41d0-9c39-59a96cf31412", pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).findPointer(7L, "demo", "production"); } @Test @@ -1057,8 +1134,6 @@ void missingCatalogRevisionIsSuppressedFromBrowseButPointerReadFailsClosed() { Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(missingRevision)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingRevision)); GameSessionGrpcService service = newService( pingService, @@ -1184,8 +1259,6 @@ void missingStableRealmIdentityIsSuppressedFromBrowseButPointerReadFailsClosed() Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(missingIdentity)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingIdentity)); GameSessionGrpcService service = newService( Mockito.mock(PingService.class), @@ -1367,7 +1440,7 @@ void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenThrow(new IllegalStateException("pointer store unavailable")); GameSessionGrpcService service = newService( From 4576b4f62c7b3a53214b77cff31442aef0461ccb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:27:50 +1300 Subject: [PATCH 09/23] Prove shipped pointer bootstrap configuration stays closed --- design/project-management/ai-observations.md | 2 +- .../realm-routing-and-playable-state.md | 2 +- ...issionPointerBootstrapInitializerTest.java | 184 ++++++++++++++++++ 3 files changed, 186 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 244853a7cd..05b30450cf 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -35,4 +35,4 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - #3369 at `208bc8488443` failed runtime-images run `41247930228` resolving Spring Boot mail starter `4.1.2`; independent Maven Central POM and JAR requests subsequently returned HTTP 200. One failed-job retry built all service jars, then failed connecting to `archive.ubuntu.com:443` during base-image APT installation despite its existing retries. These are distinct observed failures, not an application compile failure or a proven common cause. The failed logs remain in R1420 and both events were reported to Overseer. Next: qualify the unchanged image build on its next authorized retry or normal candidate run, retaining the exact failure if network access fails again; do not weaken package verification or mark remote smoke passed from local proof. - `2026-11-01` (Pacific/Auckland): CI watch masked a proven failure while another required gate was missing. - - The shared observer retained a failed required Smoke check for #3369 while another required Validation check was absent, but returned pending rather than waking for the failure. Root inspected the actual failed image-build log and reported the discrepancy to FireController Worker; the worker confirmed the precedence defect at 12:17pm NZDT and deployed correction `edc11a7b`, retaining the counts and source guards. Next: verify failure wakeup on a natural failed check; owner-focused proof is reported, but this lane has not yet observed the corrected natural failure wakeup. The pending state never supplied success. A separate Hosted wait exited locally cancelled before the provider finished; Root recovered the original operation without reposting. The owner trace could not identify the signal sender, so no server timeout or evidence loss is established. + - The shared observer retained a failed required Smoke check for #3369 while another required Validation check was absent, but returned pending rather than waking for the failure. Root inspected the actual failed image-build log and reported the discrepancy to FireController Worker; the worker confirmed the precedence defect at 12:17pm NZDT and deployed correction `edc11a7b`, retaining the counts and source guards. Natural failure wakeup is now verified: the shared observer returned the #3365/4f25 Smoke failure while Validation and CodeQL were missing, preserving the required counts. This resolved component is available for Overseer stewardship retirement; the pending state never supplied success. A separate Hosted wait exited locally cancelled before the provider finished; Root recovered the original operation without reposting. The owner trace could not identify the signal sender, so no server timeout or evidence loss is established. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 071176814a..2f03eb4f6a 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -99,7 +99,7 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. The bounded #2857 catalog/cardinality receiver has the focused R1430 proof above; a reconciled candidate and fresh source-built runtime qualification remain pending. These are historical validation facts; the decision review did not rerun them. +The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. The bounded #2857 catalog/cardinality receiver has the focused R1430 proof above; the reconciled `cb38ef94` cohort additionally passes 1,203 selected unit/integration/cross-service cases with zero failures, errors or skips, all root Checkstyle scopes on 14.4.0, Game Session SpotBugs, full formatting and documentation checks. A separate 20-case source-YAML bootstrap suite proves shipped Game Session/World target alignment, aligned environment overrides and rejection before writes when a private sandbox is moved to a tenant without public-production authority. This is mocked bootstrap proof, not persisted seed creation. Fresh combined runtime qualification remains pending. These are historical validation facts; the decision review did not rerun them. ## Active Gaps diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index cd05a5c705..ff5877b411 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -8,8 +8,12 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Arrays; import java.util.List; +import java.util.Map; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import org.junit.jupiter.api.BeforeEach; @@ -18,6 +22,12 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.env.MockEnvironment; import org.springframework.stereotype.Component; @ExtendWith(MockitoExtension.class) @@ -58,6 +68,86 @@ void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant( assertFalse(pointers.get(1).isPublicProductionRealm()); } + @Test + void shippedYamlBindsPublicDemoAndPrivateSandboxToTheSameTenantWithoutPersistingSeeds() + throws Exception { + ShippedBootstrapConfiguration shipped = loadShippedConfiguration(Map.of()); + List pointers = + shipped.gameSession().getPointers(); + + assertEquals(2, pointers.size()); + assertEquals("demo", pointers.get(0).getWorldSlug()); + assertEquals(1L, pointers.get(0).getTenantId()); + assertEquals(1L, pointers.get(0).getGameInstanceId()); + assertTrue(pointers.get(0).isVisible()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals("sandbox", pointers.get(1).getWorldSlug()); + assertEquals(1L, pointers.get(1).getTenantId()); + assertEquals(2L, pointers.get(1).getGameInstanceId()); + assertTrue(pointers.get(1).isVisible()); + assertFalse(pointers.get(1).isPublicProductionRealm()); + assertTrue(pointers.get(1).isRequiresCharacterSelection()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 1L, 1L, 1L, 2L); + + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + when(pointerRepository.count()).thenReturn(0L); + + initializer.run(new DefaultApplicationArguments(new String[] {})); + + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlTenantOverridesKeepGameSessionAndWorldTargetsAligned() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration( + Map.of( + "FIREMUD_BOOTSTRAP_DEMO_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_DEMO_GAME_INSTANCE_ID", "101", + "FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID", "202")); + List pointers = + shipped.gameSession().getPointers(); + + assertEquals(7L, pointers.get(0).getTenantId()); + assertEquals(101L, pointers.get(0).getGameInstanceId()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals(7L, pointers.get(1).getTenantId()); + assertEquals(202L, pointers.get(1).getGameInstanceId()); + assertFalse(pointers.get(1).isPublicProductionRealm()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 7L, 101L, 7L, 202L); + + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + when(pointerRepository.count()).thenReturn(0L); + + initializer.run(new DefaultApplicationArguments(new String[] {})); + + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlPrivateSandboxOverrideToAnotherTenantFailsBeforeMutation() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration(Map.of("FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "2")); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + when(pointerRepository.count()).thenReturn(0L); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + assertTrue( + failure.getMessage().contains("exactly one visible public production realm for tenant 2")); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + @Test void runPreservesExistingPointerAuthorityOnRestart() throws Exception { when(pointerRepository.count()).thenReturn(3L); @@ -235,6 +325,100 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe return pointerSeed; } + private static ShippedBootstrapConfiguration loadShippedConfiguration( + Map environmentOverrides) throws IOException { + MockEnvironment environment = new MockEnvironment(); + environment + .getPropertySources() + .addFirst(new MapPropertySource("bootstrap-test-overrides", environmentOverrides)); + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + // Read source YAML directly so test-resource shadowing cannot hide shipped defaults. + addYamlPropertySources( + environment, + loader, + "game-session-application", + "services/game-session-service/src/main/resources/application.yml"); + addYamlPropertySources( + environment, + loader, + "world-management-application", + "services/world-management-service/src/main/resources/application.yml"); + + Binder binder = Binder.get(environment); + GameplayAdmissionPointerBootstrapProperties gameSession = + binder + .bind( + "firemud.gameplay.pointer-bootstrap", + Bindable.of(GameplayAdmissionPointerBootstrapProperties.class)) + .orElseThrow(() -> new IllegalStateException("Missing Game Session bootstrap YAML")); + List worldManagementTargets = + binder + .bind( + "firemud.smoke.seed-demo-runtime.targets", + Bindable.listOf(SmokeRuntimeTarget.class)) + .orElseThrow(() -> new IllegalStateException("Missing World runtime-target YAML")); + return new ShippedBootstrapConfiguration(gameSession, worldManagementTargets); + } + + private static void addYamlPropertySources( + MockEnvironment environment, + YamlPropertySourceLoader loader, + String name, + String relativePath) + throws IOException { + loader + .load(name, new FileSystemResource(repositoryFile(relativePath))) + .forEach(environment.getPropertySources()::addLast); + } + + private static Path repositoryFile(String relativePath) { + Path directory = Path.of("").toAbsolutePath(); + while (directory != null) { + Path candidate = directory.resolve(relativePath); + if (Files.isRegularFile(candidate)) { + return candidate; + } + directory = directory.getParent(); + } + throw new IllegalStateException("Cannot locate repository file " + relativePath); + } + + private static void assertSmokeRuntimeTargets( + List actualTargets, long... expectedTenantAndInstanceIds) { + assertEquals(expectedTenantAndInstanceIds.length / 2, actualTargets.size()); + for (int index = 0; index < actualTargets.size(); index++) { + assertEquals(expectedTenantAndInstanceIds[index * 2], actualTargets.get(index).getTenantId()); + assertEquals( + expectedTenantAndInstanceIds[index * 2 + 1], + actualTargets.get(index).getGameInstanceId()); + } + } + + private record ShippedBootstrapConfiguration( + GameplayAdmissionPointerBootstrapProperties gameSession, + List worldManagementTargets) {} + + public static class SmokeRuntimeTarget { + private long tenantId; + private long gameInstanceId; + + public long getTenantId() { + return tenantId; + } + + public void setTenantId(long tenantId) { + this.tenantId = tenantId; + } + + public long getGameInstanceId() { + return gameInstanceId; + } + + public void setGameInstanceId(long gameInstanceId) { + this.gameInstanceId = gameInstanceId; + } + } + private void assertRejectedBeforeMutation( List pointers, String expectedMessage) From 3559c19bb5670d525942f86439770b7b2a4ee3f6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:38:07 +1300 Subject: [PATCH 10/23] Prove Account membership lifecycle and independent generation mapping --- .../service/impl/AccountGrpcServiceTest.java | 54 +++++++++++++++- .../service/impl/AccountServiceImplTest.java | 62 ++++++++++++++++++- 2 files changed, 110 insertions(+), 6 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 10d8482cf3..8b9ae9da40 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -2037,15 +2037,19 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); + assertEquals("1", ref.get().getTenantId()); assertTrue(ref.get().getMembershipExists()); assertTrue(ref.get().getGameplayAdmissionAllowed()); assertEquals(44L, ref.get().getMembershipVersion()); + assertEquals("ACTIVE", ref.get().getMembershipLifecycleState()); + assertEquals(9L, ref.get().getMembershipAuthorityGeneration()); + assertEquals("2026-03-30T00:00:00Z", ref.get().getEvaluatedAt()); Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); Mockito.verify(accountService).getTenantMembershipForRuntime(2L, 1L, "req-1"); } @Test - void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed() { + void getTenantMembershipForRuntimePreservesCoherentMissingMembership() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) @@ -2053,7 +2057,7 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( - 2L, 1L, false, true, 44L, "MISSING", 0L, "2026-03-30T00:00:00Z")); + 2L, 1L, false, false, 0L, "MISSING", 0L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -2071,10 +2075,54 @@ void getTenantMembershipForRuntimePreservesMissingMembershipAndAdmissionAllowed( assertNotNull(observer.response()); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("1", observer.response().getTenantId()); assertFalse(observer.response().getMembershipExists()); - assertTrue(observer.response().getGameplayAdmissionAllowed()); + assertFalse(observer.response().getGameplayAdmissionAllowed()); + assertEquals(0L, observer.response().getMembershipVersion()); + assertEquals("MISSING", observer.response().getMembershipLifecycleState()); + assertEquals(0L, observer.response().getMembershipAuthorityGeneration()); + assertEquals("2026-03-30T00:00:00Z", observer.response().getEvaluatedAt()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + } + + @Test + void getTenantMembershipForRuntimeMapsInactiveMembershipAndIndependentGenerations() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) + .thenReturn(2L); + Mockito.when(accountService.getTenantMembershipForRuntime(2L, 1L, "req-1")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.RuntimeMembershipDto( + 2L, 1L, true, false, 23L, "INACTIVE", 41L, "2026-03-30T00:00:00Z")); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + RecordingObserver observer = new RecordingObserver<>(); + + withPeer( + GAME_SESSION_PEER, + () -> + service.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId(ACCOUNT_UUID) + .setTenantId("1") + .setRequestId("req-1") + .build(), + observer)); + + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("1", observer.response().getTenantId()); + assertTrue(observer.response().getMembershipExists()); + assertFalse(observer.response().getGameplayAdmissionAllowed()); + assertEquals(23L, observer.response().getMembershipVersion()); + assertEquals("INACTIVE", observer.response().getMembershipLifecycleState()); + assertEquals(41L, observer.response().getMembershipAuthorityGeneration()); + assertEquals("2026-03-30T00:00:00Z", observer.response().getEvaluatedAt()); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); + Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); + Mockito.verify(accountService).getTenantMembershipForRuntime(2L, 1L, "req-1"); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 276e9d1fec..ff8ba33dbe 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -3914,9 +3914,12 @@ void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { account.setUsername("demo"); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); + AccountTenantMembership activeMembership = membership(account, 7L); + activeMembership.setMembershipVersion(17L); + activeMembership.setMembershipAuthorityGeneration(29L); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenReturn(Optional.of(membership(account, 7L))); + .thenReturn(Optional.of(activeMembership)); var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); @@ -3924,9 +3927,62 @@ void getTenantMembershipForRuntimeReturnsAdmissionAllowedForExistingAccount() { assertEquals(7L, dto.tenantId()); assertTrue(dto.membershipExists()); assertTrue(dto.gameplayAdmissionAllowed()); - assertEquals(1L, dto.membershipVersion()); + assertEquals(17L, dto.membershipVersion()); assertEquals("ACTIVE", dto.membershipLifecycleState()); - assertEquals(1L, dto.membershipAuthorityGeneration()); + assertEquals(29L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantMembershipForRuntimeReturnsCoherentMissingMembershipForExistingAccount() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertFalse(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(0L, dto.membershipVersion()); + assertEquals("MISSING", dto.membershipLifecycleState()); + assertEquals(0L, dto.membershipAuthorityGeneration()); + assertNotNull(dto.evaluatedAt()); + } + + @Test + void getTenantMembershipForRuntimeReturnsInactiveMembershipWithIndependentGenerations() { + Account account = new Account(); + account.setId(11L); + setPersistedAuthenticationIdentity(account); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + account.setPasswordHash(hash("password")); + AccountTenantMembership inactiveMembership = membership(account, 7L); + inactiveMembership.setGameplayAdmissionAllowed(false); + inactiveMembership.setLifecycleState("INACTIVE"); + inactiveMembership.setMembershipVersion(23L); + inactiveMembership.setMembershipAuthorityGeneration(41L); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(inactiveMembership)); + + var dto = service.getTenantMembershipForRuntime(11L, 7L, "req-1"); + + assertEquals(11L, dto.accountId()); + assertEquals(7L, dto.tenantId()); + assertTrue(dto.membershipExists()); + assertFalse(dto.gameplayAdmissionAllowed()); + assertEquals(23L, dto.membershipVersion()); + assertEquals("INACTIVE", dto.membershipLifecycleState()); + assertEquals(41L, dto.membershipAuthorityGeneration()); assertNotNull(dto.evaluatedAt()); } From c0ddf0274a97b80881c30943423557753e3695fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:38:50 +1300 Subject: [PATCH 11/23] Align membership producer status and retained receiving proof --- .../microservices/game-session-service/protocols.md | 8 ++++---- .../architecture/system-architecture-protocol-bridging.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- .../player-experience-commands-and-communication.md | 2 +- .../realm-routing-and-playable-state.md | 8 ++++---- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index f5323c8e74..2d4c36bc85 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance fails closed with `AUTH_UNAVAILABLE` before replay or admission-authority reads. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account already emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but this consumer does not enforce them and therefore does not classify `ACTIVE` or `INACTIVE`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. Current catalog receiving remains partial. Fresh Game Session catalog reads reject numeric world and realm selectors instead of interpreting them as positions in the latest list. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. @@ -41,7 +41,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, `JOIN` is unavailable and `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it cannot classify `ACTIVE` or `INACTIVE` until Account exposes lifecycle state. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and explicit `JOIN` remains unavailable; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. In the current runtime, `JOIN` is unavailable and `PLAY` applies only the Account-exposed `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` fields plus existing grant checks; it does not classify `ACTIVE` or `INACTIVE` because it ignores the emitted lifecycle field. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification, and explicit `JOIN` remains unavailable; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Current public-only `REALMS` can help disambiguate selection; direct-text `CHARS` remains unavailable. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -116,7 +116,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. It also does not expose `membershipLifecycleState`, so it uses the four-field Account adapter response (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because the adapter does not expose lifecycle state. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. It consumes only four admission-evidence fields from the Account response (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`) and cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because the consumer ignores the emitted lifecycle state. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -166,7 +166,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current implementation's persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because Account does not expose lifecycle state. +- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because the consumer ignores the lifecycle state that Account emits. - `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index aa68c015bb..389726eb91 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or `JOIN`. Explicit `JOIN`/`Join & Play` and the required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance remain unimplemented/proof gaps in the current runtime. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target flow and delivery contracts below remain normative. The complete `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` sequence remains incomplete; held-admission smoke is bounded runtime proof, not full protocol or public-admission proof. Account already emits membership lifecycle and independent authority generation/version, but current text `PLAY` ignores lifecycle/generation, evaluates membership before entitlement, and can return non-actionable public `JOIN_REQUIRED` for missing or present non-admitting membership without distinguishing `INACTIVE`. Non-public text admission uses `WORLD_ACCESS_DENIED` for membership denial and separately requires the current realm grant. Explicit text JOIN is unavailable; the Account-local writer is distinct. Current connect-token issuance validates bootstrap identity/scope and returns `AUTH_UNAVAILABLE` before cached replay, membership, entitlement or pointer reads. The complete atomic snapshot and admission authority remain unproved; current producer/issuance details are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), with capability/proof status in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect or close-taxonomy requirements. --- 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 2b918e71e7..96388ef9b3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -448,7 +448,7 @@ Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, G Official-hosted creator-content acceptance remains an unregistered target workflow. Source-only persistence now includes Creator Party and hosted-terms/environment-binding evidence plus V98 disclosure handoff and source-evidence tables; these relations do not supply external environment observation, authenticated publication, a legal authority verifier, dispatch, a consumer, registry/runtime binding, creator UI, or downstream write-gate proof. The fixed server environment-evidence adapter exists but remains deliberately unregistered and supplies no genuine input delivery. Its target authority remains under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md), outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. -Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). +Account runtime admission reads remain partial: the handlers enforce certificate-derived exact workload identities before owner access (`Game Session` for membership and the allowed runtime peers for entitlement). This does not establish the complete typed caller/verified-target binding or atomic fresh snapshot authority, which remain security/proof gaps. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index e58f7a3057..aa45e82559 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -21,7 +21,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; reconciled-candidate and fresh runtime proof remain pending. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | +| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 2f03eb4f6a..7a3c508e75 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -59,9 +59,9 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with four admission-evidence fields, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; they admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. The live Account adapter has no `membershipLifecycleState`: `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. Explicit `JOIN` / `Join & Play` remains unimplemented, and the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The live Account producer emits lifecycle state and independent authority generation/version, but current text `PLAY` consumes only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It therefore still returns non-actionable `JOIN_REQUIRED` for eligible public-production missing or present non-admitting membership without distinguishing `INACTIVE`; entitlement/public-policy precedence and lifecycle/generation enforcement remain gaps. Non-public text `PLAY` denies missing/non-admitting membership with `WORLD_ACCESS_DENIED` before its separate current realm-grant check. Current connect-token issuance validates bootstrap identity/scope and returns `AUTH_UNAVAILABLE` before cached replay or admission-authority reads. The Account-local explicit JOIN writer exists, while text JOIN dispatch and public exposure remain unavailable. R1430 separately passes all 451 cases in the two selected Account service/RPC classes, including active, missing and inactive lifecycle/independent-generation producer mapping; these mocked cases do not prove a complete atomic snapshot or consumer enforcement. Current producer, writer and issuance details remain in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md); the target atomic snapshot, explicit join and admission contract remains in [Authentication](../../architecture/system-architecture-authentication.md#in-band-play-admission-boundary). -Account bootstrap discovery has a supported HTTP character-roster capability, separate from direct-text `CHARS`; its world and realm selectors use the routing authority shared with `WORLDS` and `REALMS`. The Account roster does not make direct-text `CHARS` available or establish gameplay admission. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +Account bootstrap discovery has a supported HTTP character-roster capability, separate from unavailable direct-text `CHARS`; it does not establish gameplay admission. Current connect-token issuance is held before cached replay and fresh admission-authority processing. Its target persistence/replay and private-grant requirements remain owned by [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` retains its separate current private/playtest grant check. Neither a discovery snapshot nor a returning shortcut substitutes for complete current authority; invalid or expired scope requires fresh discovery rather than a cached target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target/unimplemented because Account direct-text `JOIN` issuance/validation and Game Session transport-local scope retention through retry, terminal outcome, or expiry still lack implementation and focused proof. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. @@ -99,13 +99,13 @@ The legacy Automation `PATCH /factions/{id}/reputation` controller has been remo ### Recorded Proof -The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. The bounded #2857 catalog/cardinality receiver has the focused R1430 proof above; the reconciled `cb38ef94` cohort additionally passes 1,203 selected unit/integration/cross-service cases with zero failures, errors or skips, all root Checkstyle scopes on 14.4.0, Game Session SpotBugs, full formatting and documentation checks. A separate 20-case source-YAML bootstrap suite proves shipped Game Session/World target alignment, aligned environment overrides and rejection before writes when a private sandbox is moved to a tenant without public-production authority. This is mocked bootstrap proof, not persisted seed creation. Fresh combined runtime qualification remains pending. These are historical validation facts; the decision review did not rerun them. +The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is target-only and is not claimed by the recorded smoke evidence. The evidence records focused proof for sequential stale-version rejection, stale-pointer rejection at connect-token issuance, verified `LOGIN`, `PLAY`, reused relogin, websocket route/selector refresh, session normalization, command staging and replay, communication availability/delivery, presence, logout, tick-state, disconnect envelopes, remote routing metadata, complete-pointer catalog/control-plane projection, world-qualified duplicate-slug lookup, operator tenant guards, and shared-versus-isolated playable-state behavior. It also records touched-service `check -PfullCheck` runs, focused Game Session/Account/Entity Management/Automation/Logging & Admin/TCP Proxy/Game Logic tests, and fresh rebuilt `bash dev-tools/verify-fresh-bootstrap.sh` proof covering the then-current abbreviated WebSocket and Telnet `LOGIN` -> `PLAY` -> `LOOK` path plus an item/container/equipment mutation extension and authenticated disconnect cleanup. That historical run does not establish the current default baseline boundary or mutating cross-transport parity. It does not prove `WORLDS`, `REALMS`, or `JOIN`, concurrent database CAS, crash recovery between pointer commit and prepared-upgrade execution marking, explicit closure, separated catalog revisions, or bounded active-session drain. The bounded #2857 catalog/cardinality receiver has the focused R1430 proof above; the reconciled `cb38ef94` cohort additionally passes 1,203 selected unit/integration/cross-service cases with zero failures, errors or skips, all root Checkstyle scopes on 14.4.0, Game Session SpotBugs, full formatting and documentation checks. A separate 20-case source-YAML bootstrap suite proves shipped Game Session/World target alignment, aligned environment overrides and rejection before writes when a private sandbox is moved to a tenant without public-production authority. This is mocked bootstrap proof, not persisted seed creation. Fresh source-built held-admission qualification at `4576b4f62c7b3a53214b77cff31442aef0461ccb` rebuilds and boots all 11 services, passes the held boundary and authenticated teardown, and independently verifies no project containers, networks or volumes remain. This is controlled preview proof, not production identity or successful public admission. These are historical validation facts; the decision review did not rerun them. ## Active Gaps - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- Explicit `JOIN`/`Join & Play` remains unimplemented. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; an eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because the live adapter does not expose lifecycle state. The target membership-authority-generation reread at issuance remains a gap. +- Text `JOIN`/`Join & Play` dispatch remains unimplemented; the Account-local explicit writer is separate. Text `PLAY` still ignores Account-emitted lifecycle/generation and evaluates membership before entitlement/public-policy gates. Current connect-token issuance remains held before replay/authority reads. Complete atomic snapshot authority, current lifecycle/generation consumption, and the canonical outcome order remain gaps; no membership is created implicitly. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. From b223ae36ae96319b6d963713b547f1a0d24b035a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:19:51 +1300 Subject: [PATCH 12/23] Qualify retained-row helpers and canonical design evidence --- ...er-experience-commands-and-communication.md | 2 +- ...ssionPointerCardinalityIntegrationTest.java | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index aa45e82559..d651b1d66f 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -21,7 +21,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | +| EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm catalog and admission pointers](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java index 3482c6ccde..4d1442216d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.test.TestContainerImages; @@ -241,11 +242,13 @@ private static List retainedRowsAndXmins(DSLContext dsl, String tableNam } private static String rowAndXmin(DSLContext dsl, long pointerId) { - return dsl.fetchOne( - "SELECT xmin::text || ':' || " - + "encode(convert_to(to_jsonb(pointer)::text, 'UTF8'), 'hex') " - + "FROM gameplay_admission_pointer AS pointer WHERE id = ?", - pointerId) + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text || ':' || " + + "encode(convert_to(to_jsonb(pointer)::text, 'UTF8'), 'hex') " + + "FROM gameplay_admission_pointer AS pointer WHERE id = ?", + pointerId), + "Expected the retained admission pointer row") .get(0, String.class); } @@ -274,7 +277,10 @@ private static long visiblePublicCount(DSLContext dsl, long tenantId) { } private static long scalarLong(DSLContext dsl, String query, Object... bindings) { - return dsl.fetchOne(query, bindings).get(0, Long.class); + return Objects.requireNonNull( + Objects.requireNonNull(dsl.fetchOne(query, bindings), "Expected one scalar query row") + .get(0, Long.class), + "Expected a non-null scalar query value"); } private static void assertUniqueIndexViolation(Runnable statement) { From 0f93b0b0479fef924663f05e652f9e4c45b1c65b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:53:24 +1300 Subject: [PATCH 13/23] Resolve typed numeric slugs and align session review evidence --- .../game-session-service/protocols.md | 4 +- .../game-session-service/runtime-and-data.md | 2 +- .../tcp-proxy-service/api-contracts.md | 2 +- .../system-architecture-protocol-bridging.md | 6 +- .../system-architecture-reconnection.md | 4 +- .../system-architecture-session-behavior.md | 2 +- .../player-access-and-session.md | 2 +- ...r-experience-commands-and-communication.md | 16 +-- .../realm-routing-and-playable-state.md | 2 +- .../command/text/GameplayWorldCatalog.java | 15 +-- .../command/text/HelpCommandHandler.java | 1 - .../command/text/PlayCommandHandler.java | 16 ++- .../command/text/WorldsCommandHandler.java | 9 ++ .../text/GameplayWorldCatalogTest.java | 33 ++++- .../command/text/HelpCommandHandlerTest.java | 2 +- .../command/text/PlayCommandHandlerTest.java | 124 ++++++++++++++++++ .../text/WorldsCommandHandlerTest.java | 43 ++++++ .../impl/GameSessionGrpcServiceTest.java | 27 ++++ 18 files changed, 268 insertions(+), 42 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 2d4c36bc85..b22a33de12 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,7 +14,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance fails closed with `AUTH_UNAVAILABLE` before replay or admission-authority reads. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account already emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but this consumer does not enforce them and therefore does not classify `ACTIVE` or `INACTIVE`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. -Current catalog receiving remains partial. Fresh Game Session catalog reads reject numeric world and realm selectors instead of interpreting them as positions in the latest list. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. +Current catalog receiving remains partial. Direct-text handlers reject unbound numeric world and realm menu selectors instead of interpreting them as positions in the latest list; typed catalog and admission APIs resolve exact canonical slugs, including numeric-only slugs. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current catalog-side world and realm resolution refuses numeric selectors because transport-local menu retention is not wired into these readers. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current direct-text handling refuses unbound numeric world and realm menu selectors because transport-local menu retention is not wired into that flow. Exact typed slug readers do not reinterpret numeric slugs as menu positions. ### JOIN Translation and Status diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 0b17b00c44..5c0cba1ece 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -34,7 +34,7 @@ The sections below define the target-state runtime contract. Current implementat - **Direct-text WORLDS menu retention:** the manually composed menu store and one-key Redis script retain only the public `WORLDS` UI snapshot under the tenantless proxy-UUID family. The numeric transport session ID and the exact observed proxy UUID remain separate correlation values; neither an observed UUID nor Redis `ACL WHOAMI` establishes authenticated receiving custody or LOGIN/JOIN authority. Missing, expired, reset, or source-stale menu state requires a fresh `WORLDS` request and cannot recreate or clear authentication state. Production protected-connection binding, receiving-chain provenance and hidden rebind remain gaps; the source has no deployed ACL change. Focused component and physical Redis proof is recorded in the owning tracker, without establishing genuine receiving custody or registration. See [the Redis menu contract](../../system-architecture-redis.md#direct-text-worlds-ui-menu) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). -- **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while fresh numeric selectors and ambiguous private defaults are refused. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). +- **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while direct-text unbound numeric menu selectors and ambiguous private defaults are refused. Exact typed slug reads accept canonical numeric-only slugs without fresh-list indexing. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. diff --git a/design/architecture/microservices/tcp-proxy-service/api-contracts.md b/design/architecture/microservices/tcp-proxy-service/api-contracts.md index 69e558e908..44e4346046 100644 --- a/design/architecture/microservices/tcp-proxy-service/api-contracts.md +++ b/design/architecture/microservices/tcp-proxy-service/api-contracts.md @@ -6,7 +6,7 @@ After actual edge loss, the Telnet transport carries the owner-defined `WORLDS` ## Implementation Status -Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; the live Account adapter does not expose lifecycle state, so missing and `INACTIVE` membership cannot be distinguished by the current implementation. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. Its current Game Session receiver returns bounded acknowledgements after read-only metadata checks without suspending shared state or invoking presence effects; [Game Session runtime status](../game-session-service/runtime-and-data.md#reconnection-and-disconnect-handling) records that containment and its remaining binding-fence limits. +Current proxy routing and receiving-service behavior support an abbreviated returning-member `LOGIN` -> `PLAY` path when current membership and character gates pass. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite; Account emits lifecycle state and an independent membership-authority generation, but the current text `PLAY` consumer does not enforce those fields; see [Account runtime status](../account-service/runtime-and-data.md). The proxy does not classify membership lifecycle. `NotifyDisconnect` remains a best-effort, at-least-once advisory signal as described below. Its current Game Session receiver returns bounded acknowledgements after read-only metadata checks without suspending shared state or invoking presence effects; [Game Session runtime status](../game-session-service/runtime-and-data.md#reconnection-and-disconnect-handling) records that containment and its remaining binding-fence limits. ## Service Interactions diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 389726eb91..aa4076062e 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Account connect-token issuance separately fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay or token work; [Account runtime status](./microservices/account-service/runtime-and-data.md) owns the current endpoint boundary. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current runtime has no lifecycle-state predicate: its current admission fields are `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current text `PLAY` does not consume the Account producer’s emitted lifecycle/generation fields; its boolean admission predicate does not prove the target lifecycle gate. Direct-text `CHARS` is unavailable, while the separate Account HTTP/bootstrap roster does not complete that command boundary. Current connect-token issuance is fail-closed rather than a completed shortcut/token path; successful target character, grant, pointer and issuance ordering remains incomplete. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable while explicit `JOIN` is unimplemented. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable while explicit `JOIN` is unimplemented. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token endpoint currently returns `AUTH_UNAVAILABLE` before membership checks; target membership-dependent issuance outcomes are not current behavior. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from current Account endpoint behavior. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index af8ab92554..a3f9572c43 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current Account connect-token issuance fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, or replay work; see [Account runtime status](./microservices/account-service/runtime-and-data.md). Current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, but not the Account producer’s emitted `membershipLifecycleState` or independent `membershipAuthorityGeneration`. Its boolean admission predicate does not establish the target `ACTIVE` lifecycle requirement; missing or non-admitting public-production membership can produce non-actionable `JOIN_REQUIRED` before complete target ordering is enforced. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. Explicit `JOIN`/`Join & Play` and the required connect-token membership-authority/version rereads remain unimplemented/proof gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. - **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. Current WebSocket reconnect suppresses retained private-context presentation rather than retrieving or sending screen-buffer entries; rows remain stored while durable episode/generation eligibility is unqualified. It obtains a fresh authoritative `LOOK` when reconnect redraw is recommended or the exact mode is `first_party_web`, and emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. The target reconnect sequence still renders eligible retained context after authorization, then obtains fresh `LOOK` and emits exactly one reconnect prompt when both settings are enabled (zero when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -224,7 +224,7 @@ Clients must also treat pre-disconnect input and output as non-resumable transpo The close reason never establishes that command outcome. The current gameplay-command status surfaces are restricted to authorized operator or internal-service clients; an authorized client holding `{tenantId, gameInstanceId, commandId}` may reconcile that tuple, but ordinary players cannot use knowledge of `commandId` to query it. A future caller-bound first-party status route may expose the same authoritative record only after it binds the requested tuple to the immutable ingress account, character, or session identity required by the owning [command-outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required). Until that route exists, ordinary browser and classic line clients receive later state reconstruction, must not treat any retryable close as proof that the last command failed, and must not recreate the input automatically. -- current implementation persists ordered `resume_transcript_entry` rows and can best-effort freshly render available retained context after a binding-checked eligible reconnect. Current first-party post-logout suppression is not enforced, so retained context can still replay after `LOGOUT`. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; +- current implementation persists ordered `resume_transcript_entry` rows but suppresses retained private-context presentation while durable episode and `resumeContextGeneration` eligibility is unqualified. Rows remain stored; presentation suppression is not durable `LOGOUT` invalidation, and current first-party `LOGIN`/`PLAY` deny before legacy effects. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; - the context may repeat output the client already displayed or omit output that was not retained or available. It is not a delivery acknowledgement, exact missed-message list, command history, or transcript archive; Redis may cache it but is not authoritative, and physical deletion may complete asynchronously; - then current reconnect flow obtains a fresh authoritative `LOOK` and applies the owner-defined prompt behavior. The local consequence is exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero when either is disabled; prompt restoration and duplicate-prevention proof remain current gaps recorded in [Input, Output and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status). This reconstruction defines current state; retained context is narrative orientation only. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index ad7cb7743c..2f2089da19 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -30,7 +30,7 @@ Retained per-sequence duplicate evidence is a separate same-snapshot carrier, no ## Implementation Status -Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `evaluatedAt`, and `error`; the current Game Session `PLAY` path consumes that response, while roles, the target exact one-tenant `membershipVersion` map carrier, `membershipAuthorityGeneration`, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. +Membership-change event delivery and generation-aware session consumption are not yet live. The current `GetTenantMembershipForRuntimeResponse` and `AccountGrpcService` producer expose `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, `evaluatedAt`, and `error`; current Game Session `PLAY` consumes only the admission booleans, version, and evaluation time, without enforcing the emitted lifecycle or independent generation. Roles, the target exact one-tenant `membershipVersion` map carrier, `authorityTuple`, `outboxCheckpoints`, Account event delivery, generation-aware consumers, same-stream reconciliation, remaining player-facing legacy mapping, and focused proof across admission/reconnect paths remain gaps. The versioned Account-owned token-registry rules and binding schema below are target state, not current runtime behavior: the current fallback uses the legacy Account session key rather than the canonical issued-token registry. Game Session must not treat the contract below as fully implemented until those fields, consumers, and proofs converge. The target Account-durable-intent-before-Gateway-marker logout ordering and final Account token-fence invalidation are also not currently proven; the current fallback is Account logout plus local cleanup and bounded expiry, not proof of complete logout. The current WebSocket reconnect path does not retrieve or send retained private screen-buffer/context entries; private-context presentation is temporarily suppressed while durable episode and `resumeContextGeneration` eligibility remains unqualified. The rows remain stored, so this is not deletion or proof of durable logout invalidation. When a reconnect redraw is recommended or the exact mode is `first_party_web`, reconnect obtains a fresh authoritative `LOOK`; it emits a reconnect prompt only when both effective reconnect-prompt settings are enabled. This is current implementation status, not a change to the target eligible-context sequence owned by [Reconnection](./system-architecture-reconnection.md) and [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md). 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 29cdd497f2..f5f7d52d2c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -478,7 +478,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The local reader refuses null, missing, ambiguous or nonpositive-version subscription evidence. Classified storage outages preserve `ENTITLEMENT_UNAVAILABLE`; JOIN diagnostic persistence follows rollback, and terminal-outage reads preserve the complete original receipt. The focused current-source qualification is recorded below. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance returns `AUTH_UNAVAILABLE` before entitlement reads, cached replay or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | -| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. Focused receiving proof of this suppression and redraw behavior remains pending. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | +| `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery requires membership permitting gameplay admission without an Entity read; connect-token issuance instead returns `AUTH_UNAVAILABLE` before membership or cached-success replay. Pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof now covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Account-owned explicit public-production JOIN writing and operation checks are implemented locally; first-party text JOIN dispatch, lifecycle-aware inactive membership, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index d651b1d66f..333d020bb7 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. Game Session currently has no independently verified gameplay-grant carrier, so newly written and returned presence uses the ordinary `PLAYER` projection; retained elevated cache values are presented as `PLAYER` until an ordinary presence update replaces them. Read-side demotion does not persist a change or extend TTL. R1423 qualifies this bounded receiving projection, with the source and recovery limits recorded below. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. Game Session currently has no independently verified gameplay-grant carrier, so newly written and returned presence uses the ordinary `PLAYER` projection; retained elevated cache values are presented as `PLAYER` until an ordinary presence update replaces them. Read-side demotion does not persist a change or extend TTL. R1423 qualifies this bounded receiving projection, with the source and recovery limits recorded below. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable logout invalidation, and broader client consumption are not yet proven. The earlier first-party post-`LOGOUT` replay defect is historical: current first-party `LOGIN`/`PLAY` deny and WebSocket reconnect suppresses retained private-context presentation. Durable logout invalidation and episode/generation-qualified replay remain gaps; stored rows are preserved. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. @@ -15,7 +15,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] - The [Social UUID preparation boundary](#communication-social-and-presence) temporarily rejects parent-issued numeric callers and has incompatible outbound peer readers; final supported UUID behavior is restored through #3360 and #2972, with service-local safety gaps still explicit. - Friend-presence reads still lack snapshot-bound pagination and bounded-page proof; complete these against the [Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#friend-presence-privacy-contract). - Friend-presence continuation still needs current friendship and block-state revalidation; complete this against the [Friend Presence Privacy Contract](../../architecture/microservices/social-groups-service/api-contracts.md#target-state-snapshot-chunking-pagination-and-failure-precedence). -- Game Session has no independently verified gameplay-grant carrier today, so presence currently uses `PLAYER`; the received correction has not yet had its focused proof executed on this head. Production tenant-gameplay-grant qualification, admission, and broader runtime authorization/disclosure proof remain incomplete under [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and the canonical [authentication owner](../../architecture/system-architecture-authentication.md). +- Game Session has no independently verified gameplay-grant carrier today, so presence currently uses `PLAYER`; R1423 executed bounded receiving proof during the preparation committed as `d12c0ab2e7a7d1d40f62991e3d097bd9090cc2ef` (137 selected units plus six real-Redis cases; original aggregate and fixture recovery are distinguished below). That proof was not rerun on the current review head. Production tenant-gameplay-grant qualification, admission, and broader runtime authorization/disclosure proof remain incomplete under [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md) and the canonical [authentication owner](../../architecture/system-architecture-authentication.md). ## Capability Status @@ -23,7 +23,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm catalog and admission pointers](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; current reconnect suppresses private-context presentation and current first-party LOGIN/PLAY deny; durable episode/generation-qualified replay and logout invalidation remain unproved. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - previously recorded focused evidence remains attributed to its original sources; R1423 qualifies PLAYER-only creation/projection, cached-role read projection without persisting demotion or extending presence TTL, and ordinary field-preserving updates. Snapshot-bound pagination, current friendship/block revalidation, bounded-page proof, and production tenant-gameplay-grant qualification also remain incomplete. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [RedisGameplayPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java); [RedisAccountRecentPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java); [AccountClient.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [WhoCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java); [RedisAccountRecentPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java); [AccountClientTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Current Game Session has no independently verified gameplay-grant carrier, so new and returned presence uses `PLAYER`; JWT global/scoped claims and retained elevated cache roles do not elevate a presence projection. Read-side role demotion is projection-only and does not persist the role change or extend presence TTL; ordinary activity updates persist `PLAYER` while preserving the other presence fields. R1423 qualifies this bounded behavior through the Redis, WHO/reconnect units and real-Redis cases described below. Complete snapshot-bound pagination, current relationship/block revalidation, bounded-page proof, production tenant-gameplay-grant qualification, and broader authorization/disclosure proof remain open. Keep in-world concealment under gameplay policy before calling this capability proven. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | @@ -50,9 +50,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance instead validates bootstrap identity and retained scope, then fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay, or token work; [Account runtime status](../../architecture/microservices/account-service/runtime-and-data.md) owns that current behavior. Target membership-authority-generation rereads and successful issuance remain gaps. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also refuses numeric selectors on fresh catalog reads and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings remain bounded current behavior; R1424 qualifies the bounded HELP/PLAY and WebSocket containment while preserving those existing outcomes. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also refuses unbound numeric menu selectors at text entry boundaries while typed APIs resolve exact canonical numeric-only slugs and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior remains bounded current behavior; Account connect-token issuance remains unavailable before membership or policy evaluation. R1424 qualifies bounded HELP/PLAY and WebSocket containment, not successful issuance or target admission ordering. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation @@ -62,8 +62,8 @@ The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHA ### Transcript, History, and Room Views -- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage, but the first-party connect-context replay handler currently ignores that eligibility and may replay retained rows; durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). -- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. The handler-side eligibility check owns the post-logout suppression fix; post-logout first-party replay still contradicts canonical termination behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. +- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage. Current WebSocket reconnect suppresses retained private-context retrieval/presentation and first-party LOGIN/PLAY deny before legacy effects; durable retained rows remain stored and are distinct from reconnect eligibility or durable logout invalidation. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. R1424 separately qualifies the bounded suppression and fresh LOOK/prompt path; the target episode/generation eligibility check and durable logout invalidation remain unproved. Full transcript archive/export and player-controlled history export remain incomplete; raw transport-byte replay is not supported. - Current behavior: Game Logic composes ordinary floor-free `LookResult` data from World Management and Entity Management; Game Session enforces access and renders the result. Current request/proto evidence carries no causal-floor evidence, so target propagation and participant proof remain gaps linked to [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). `LOOK`, `QUICKLOOK`, movement refresh, localization, brief/color handling, and bounded error mapping are covered. The current renderer also writes disposable legacy cache values; reads remain authoritative/uncached, and this incomplete scope plus ten-minute TTL does not prove the target causal-floor/freshness contract. Combat-sensitive brief-on-move and broader world-content localization remain incomplete. ### Communication, Social, and Presence @@ -76,7 +76,7 @@ At this preparation stage, Social sends UUIDs to five outbound peer operations w Focused source proof covers complete Common Security and Social unit suites, native Social application cases, and seven physical PostgreSQL migration/repository cases preserving parent history and refusing populated legacy tables. Later selected proof covers mail caller refusal, Account response correlation and the access guard. The most recent complete unit tasks reused retained results rather than executing freshly; canonical schema, enabled analysis, formatting and documentation checks also pass. Exact run history, failures and recoveries remain in the review records. These separate proofs do not establish whole-composition or real-service gameplay safety. Current-head CI, independent review and fresh-image smoke remain separate obligations; production custody, registration, admission and activation holds remain with [Player Access and Session](./player-access-and-session.md#social-uuid-receiver-preparation). -- Previously recorded focused unit, native application and WebSocket composition evidence covers bounded presence-owner correlation, the earlier tenant-scoped classification, profile-policy projection and player-facing output corrections; its exact run attribution remains in the review records. The current receiving source changes make Game Session presence PLAYER-only while no independent gameplay-grant carrier is available, and add cached-role projection plus ordinary-update demotion. R1423 passes 137 selected Common/Game Session units, including Redis presence, WHO and reconnect cases, plus six actual-Redis cases using the production serializer. Its physical cache cases compare retained bytes and TTL through session, game and account reads before field-preserving activity demotion. The initial aggregate fails only new integration-fixture mutable-long analysis; immutable per-case IDs recover all six physical cases and enabled integration static analysis, formatting and documentation. Earlier unit/main-analysis results keep their source attribution; these scoped results do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md), the [authentication owner](../../architecture/system-architecture-authentication.md), and the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md) own the target behavior. +- Previously recorded focused unit, native application and WebSocket composition evidence covers bounded presence-owner correlation, the earlier tenant-scoped classification, profile-policy projection and player-facing output corrections; its exact run attribution remains in the review records. The current receiving source changes make Game Session presence PLAYER-only while no independent gameplay-grant carrier is available, and add cached-role projection plus ordinary-update demotion. R1423’s receiving preparation, committed as `d12c0ab2e7a7d1d40f62991e3d097bd9090cc2ef`, executed 137 selected Common/Game Session units, including Redis presence, WHO and reconnect cases, plus six actual-Redis cases using the production serializer. Its retained `qualification.log` and `recovery.log` distinguish the original aggregate failure from fixture recovery; these are preparation-time results, not a rerun on the current review head. Its physical cache cases compare retained bytes and TTL through session, game and account reads before field-preserving activity demotion. The initial aggregate fails only new integration-fixture mutable-long analysis; immutable per-case IDs recover all six physical cases and enabled integration static analysis, formatting and documentation. Earlier unit/main-analysis results keep their source attribution; these scoped results do not establish full native-service, production gameplay-grant or admission proof. Snapshot-bound continuation, current relationship/block revalidation and broader authorization/disclosure remain incomplete. [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md), the [authentication owner](../../architecture/system-architecture-authentication.md), and the [Game Session runtime/data owner](../../architecture/microservices/game-session-service/runtime-and-data.md) own the target behavior. - Guild creation/member lifecycle callbacks emit best-effort operational logs after commit, with no committed lifecycle event on rollback. This logging supplies no durable audit or delivery guarantee. Consolidated receiving R1137 passes all 109 Social unit cases and all 15 selected native application cases, including the 12 `GuildServiceImplTest` cases covering all four actions, commit-versus-rollback context and a scoped throwing-appender regression. Enabled affected main/test/integration analysis, formatting and documentation checks pass. This proves the local dispatch boundary and supported service seams, not durable audit, delivery guarantees or current published-head/fresh-image qualification. - Current behavior/proof: `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, mail APIs, friends, guild APIs, presence reads, privacy settings, recipient delivery, and speech normalization are live at bounded service/API seams; focused communication, social, presence, privacy, moderation, and cross-service tests cover those seams. - Local gaps linked to [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md) include offline `TELL`, profile-scoped `SHOUT`, richer topology/interception, type-specific history/acknowledgement, entity-owned social value/attachments, closed observer views, cross-pod delivery, first-party recipient presentation, and the canonical gameplay `WHISPER` recipient-scope migration. These ADR links identify gaps; they do not restate target policy. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 7a3c508e75..c6ddb18f22 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -51,7 +51,7 @@ The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer a `GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. It groups rows by `{tenantId, worldSlug, realmSlug}` and emits a visible catalog entry only for exactly one complete row in that tenant-qualified selector scope. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target; duplicate selector rows within a tenant, duplicate runtime matches, and incomplete rows disappear from player-facing catalog projection rather than selecting an arbitrary row. -The current local #2857 receiver correction keeps the catalog-side boundary fail-closed: numeric selectors are refused by fresh reads, and composed `PLAY`/`WORLDS` decisions use one immutable catalog snapshot. Public/caller-free realm snapshots contain only public-production realms, private-only defaults are not inferred when ambiguous, and `GetAdmissionPointer` validates the selected slug tuple against one actual tenant pointer-list response. This does not wire in the separate exact-target direct-text UUID menu store or establish complete canonical `tenantSlug/worldSlug` support; authenticated private `REALMS` retention, protected receiving, explicit `JOIN`, and first-party admission remain gaps. R1430 passes 293 selected command/catalog/gRPC unit cases and 11 actual PostgreSQL migration cases, with no failures, errors or skips, plus canonical jOOQ generation and enabled service static/format checks. The initial migration test compilation failure was corrected before the separate physical run; the retained unit result and successful migration result are distinct runs. `AA-3.1`/`AA-3.3` remain partial and `drift-found` because the complete target is still absent. V1053 adds only a forward partial unique guard for visible public-production pointer cardinality per tenant; zero remains physically representable and is rejected by current readers, while the current realm catalog and V12/V13 are unchanged. The two new PostgreSQL cases prove successful existing-data migration, unchanged retained rows/events and migration history, rejection of duplicate visible public-production rows, and atomic refusal for pre-existing duplicate authority; nine existing pointer-migration cases also pass. +The current local #2857 receiver correction keeps the catalog-side boundary fail-closed: unbound numeric menu selectors are refused at text entry boundaries, exact typed slug reads accept canonical numeric-only world/realm slugs without indexing a fresh list, and composed `PLAY`/`WORLDS` decisions use one immutable catalog snapshot. Public/caller-free realm snapshots contain only public-production realms, private-only defaults are not inferred when ambiguous, and `GetAdmissionPointer` validates the selected slug tuple against one actual tenant pointer-list response. This does not wire in the separate exact-target direct-text UUID menu store or establish complete canonical `tenantSlug/worldSlug` support; authenticated private `REALMS` retention, protected receiving, explicit `JOIN`, and first-party admission remain gaps. R1430 passes 293 selected command/catalog/gRPC unit cases and 11 actual PostgreSQL migration cases, with no failures, errors or skips, plus canonical jOOQ generation and enabled service static/format checks. The initial migration test compilation failure was corrected before the separate physical run; the retained unit result and successful migration result are distinct runs. `AA-3.1`/`AA-3.3` remain partial and `drift-found` because the complete target is still absent. V1053 adds only a forward partial unique guard for visible public-production pointer cardinality per tenant; zero remains physically representable and is rejected by current readers, while the current realm catalog and V12/V13 are unchanged. The two new PostgreSQL cases prove successful existing-data migration, unchanged retained rows/events and migration history, rejection of duplicate visible public-production rows, and atomic refusal for pre-existing duplicate authority; nine existing pointer-migration cases also pass. Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 7f5cdd8e94..ee3f9370cb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -84,8 +84,8 @@ public Optional resolveWorld(String selector) { } private Optional resolveWorld(String selector, CatalogSnapshot snapshot) { - // A catalog read has no transport-local menu. Numeric input must be resolved by the - // retained selection owner, never against the ordering of a fresh catalog response. + // Typed slug lookup never interprets a selector as an index into this fresh snapshot. + // Unbound ordinal refusal belongs to the text command entry points. return resolveWorldBySlug(selector, visibleWorlds(snapshot)); } @@ -191,9 +191,6 @@ private Optional resolveWorld(String selector, List worlds } private Optional resolveWorldBySlug(String selector, List worlds) { - if (isOrdinalSelector(selector)) { - return Optional.empty(); - } String normalized = selectorKey(selector); List matches = worlds.stream().filter(world -> normalized.equals(selectorKey(world.slug()))).toList(); @@ -201,7 +198,7 @@ private Optional resolveWorldBySlug(String selector, List } public Optional resolveRealm(WorldView world, String selector) { - if (world == null || selector == null || selector.isBlank() || isOrdinalSelector(selector)) { + if (world == null || selector == null || selector.isBlank()) { return Optional.empty(); } String normalized = selectorKey(selector); @@ -215,11 +212,7 @@ public Optional resolveRealm(WorldView world, String selector) { // Admission may resolve hidden realms, but callers must still perform membership and grant // checks. Optional resolveRealmForAdmission(WorldView world, String selector) { - if (world == null - || selector == null - || selector.isBlank() - || isOrdinalSelector(selector) - || world.realms() == null) { + if (world == null || selector == null || selector.isBlank() || world.realms() == null) { return Optional.empty(); } String normalized = selectorKey(selector); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index ec2ee9f19f..1d411e6b68 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -99,7 +99,6 @@ public TextCommandInterpretationResult handle( success( "WHO\n" + "List currently connected players in this game instance.\n" - + "Gods appear first, then players.\n" + "You must already be in-world with PLAY."); case "STATUS" -> success( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 0474bec4f0..f49f5c4ba8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -251,8 +251,10 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } Optional maybeRealm = selection.explicitRealmSelector() != null - ? gameplayWorldCatalog.resolveRealmForAdmission( - selectedWorld, selection.explicitRealmSelector()) + ? GameplayWorldCatalog.isOrdinalSelector(selection.explicitRealmSelector()) + ? Optional.empty() + : gameplayWorldCatalog.resolveRealmForAdmission( + selectedWorld, selection.explicitRealmSelector()) : selectDefaultRealm(selectedWorld, catalogSnapshot); if (maybeRealm.isEmpty()) { return failure( @@ -563,7 +565,7 @@ private PlayerOutput successNotice( "Entered world: " + displaySelection + characterSuffix, "notice.world.entered", Map.of( - "worldName", world.slug(), + "worldName", displaySelection, "realmName", realm.slug(), "characterSuffix", characterSuffix)); } @@ -1014,7 +1016,8 @@ private Optional resolveSelection( TextCommandPayload.PlayRequest playRequest, GameplayWorldCatalog.ReadSnapshot catalogSnapshot) { String worldSelector = playRequest.worldSelector(); - if (!StringUtils.hasText(worldSelector)) { + if (!StringUtils.hasText(worldSelector) + || GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { return Optional.empty(); } String secondSelector = @@ -1034,7 +1037,10 @@ private Optional resolveSelection( catalogSnapshot.resolveWorld(worldSelector); if (maybeWorld.isPresent() && StringUtils.hasText(secondSelector) - && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { + && (GameplayWorldCatalog.isOrdinalSelector(secondSelector) + || !gameplayWorldCatalog.hasRealmForAdmission( + maybeWorld.orElseThrow(), secondSelector))) { + // A numeric second argument remains a character name, never an unbound realm ordinal. return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), null, secondSelector)); } return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 702b7128be..fc622d35af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -26,6 +26,9 @@ public WorldsViewOutput browseView() { } public java.util.Optional browseRealms(String worldSelector) { + if (GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { + return java.util.Optional.empty(); + } return worldCatalog.browseRealms(worldSelector); } @@ -35,6 +38,9 @@ public CharacterBrowseResult browseCharacters( if (!sessionContext.hasAccountIdentity()) { return CharacterBrowseResult.unavailable(); } + if (GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { + return CharacterBrowseResult.invalidWorld(); + } GameplayWorldCatalog.ReadSnapshot snapshot = worldCatalog.readSnapshot(); java.util.Optional maybeWorld = snapshot.resolveWorld(worldSelector); @@ -42,6 +48,9 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.invalidWorld(); } GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); + if (GameplayWorldCatalog.isOrdinalSelector(realmSelector)) { + return CharacterBrowseResult.invalidRealm(world.slug()); + } java.util.Optional maybeRealm = StringUtils.hasText(realmSelector) ? worldCatalog.resolveRealm(world, realmSelector) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index f7f195c306..68e4d67386 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1127,7 +1127,7 @@ void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { } @Test - void numericWorldSelectionRequiresARetainedTransportMenuRatherThanAFreshCatalog() { + void numericSlugLookupDoesNotIndexFreshCatalogOrdering() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -1163,13 +1163,38 @@ void commandReadSnapshotUsesOneActualPointerListForSelectionDefaultAndCardinalit } @Test - void unboundNumericRealmSelectorsCannotBecomeRealmSlugs() { + void typedNumericWorldAndRealmSlugsResolveExactlyRatherThanAsPositions() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("123", "456", 7L, true), + worldWithRealm("demo", "production", 8L, true))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("123").orElseThrow(); + + assertThat(world.slug()).isEqualTo("123"); + assertThat(catalog.readSnapshot().resolveWorld("123")).contains(world); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("123")).contains(world); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("123")).contains(world); + assertThat(catalog.browseRealms("123").orElseThrow().realms().getFirst().realmSlug()) + .isEqualTo("456"); + assertThat(catalog.resolveRealm(world, "456")).contains(world.realms().getFirst()); + assertThat(catalog.resolveRealmForAdmission(world, "456")).contains(world.realms().getFirst()); + assertThat(catalog.resolveWorld("1")).isEmpty(); + assertThat(catalog.resolveWorld("2")).isEmpty(); + assertThat(catalog.resolveRealm(world, "1")).isEmpty(); + assertThat(catalog.resolveRealmForAdmission(world, "1")).isEmpty(); + } + + @Test + void typedNumericRealmSlugResolvesExactlyWithoutOrdinalFallback() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of(worldWithRealm("demo", "1", 7L, true))); GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); - assertThat(catalog.resolveRealm(world, "1")).isEmpty(); - assertThat(catalog.resolveRealmForAdmission(world, "1")).isEmpty(); + assertThat(catalog.resolveRealm(world, "1")).contains(world.realms().getFirst()); + assertThat(catalog.resolveRealmForAdmission(world, "1")).contains(world.realms().getFirst()); + assertThat(catalog.resolveRealm(world, "2")).isEmpty(); + assertThat(catalog.resolveRealmForAdmission(world, "2")).isEmpty(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index ef49ce40bb..5303eae932 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -79,7 +79,7 @@ void helpWhoTopicExplainsGameplayOnlyScope() { .get(0) .text() .contains("List currently connected players in this game instance.")); - assertTrue(result.outputs().get(0).text().contains("Gods appear first, then players.")); + assertFalse(result.outputs().get(0).text().contains("Gods appear first")); assertTrue(result.outputs().get(0).text().contains("You must already be in-world with PLAY.")); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index af8a5ae8f9..91a46a4d6f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -172,6 +172,130 @@ void setUp() { }); } + @ParameterizedTest + @ValueSource(strings = {"1", "123", "2"}) + void playRefusesUnboundNumericWorldEvenWhenExactSlugExists(String selector) { + gameplayCatalogProperties.getWorlds().getFirst().setSlug(selector); + SessionContext existing = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(existing)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY " + selector)); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_MESSAGE); + verifyNoGameplayBindingSideEffects(); + Mockito.verify(sessionContextService, never()) + .deleteBySessionId(Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + gameplayPresenceLifecycleService); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "123"}) + void playRefusesUnboundNumericExplicitRealmEvenWhenExactSlugExists(String selector) { + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setSlug(selector); + SessionContext existing = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(existing)); + + var result = + handler.handle( + "1", new TextCommandParser().parse("PLAY sandbox " + selector + " Emberline")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo( + "Selection required. Use PLAY sandbox [character] or browse REALMS first."); + verifyNoGameplayBindingSideEffects(); + Mockito.verify(sessionContextService, never()) + .deleteBySessionId(Mockito.anyLong(), Mockito.anyLong()); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + gameplayPresenceLifecycleService); + } + + @ParameterizedTest + @ValueSource(strings = {"PLAY demo 1", "PLAY demo production 1"}) + void numericCharacterNameStillResolvesExactlyEvenWhenANumericRealmExists(String command) { + // A hidden numeric realm is available to admission lookup but must not steal a character name. + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .add(realm("1", "Hidden Realm", 22L, 41L, false, true)); + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "1", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + var result = handler.handle("1", new TextCommandParser().parse(command)); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as 1"); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.gameInstanceId() == 1L + && saved.realmSlug().equals("production") + && saved.characterId() == 7001L + && saved.characterName().equals("1"))); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + + @ParameterizedTest + @ValueSource(strings = {"PLAY demo 1", "PLAY demo production 1"}) + void numericCharacterSelectorNeverIndexesAFreshRoster(String command) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = handler.handle("1", new TextCommandParser().parse(command)); + + // The sole roster actor is named demo, not 1. + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); + } + + @ParameterizedTest + @CsvSource({"PLAY demo,demo,demo", "PLAY sandbox preview Emberline,sandbox (preview),Emberline"}) + void localizedEntryNoticePreservesPublicAndPrivateDisplaySelection( + String command, String displaySelection, String character) { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = handler.handle("1", new TextCommandParser().parse(command)); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + PlayerOutput notice = result.outputs().getFirst(); + String suffix = " as " + character; + assertThat(notice.text()).isEqualTo("Entered world: " + displaySelection + suffix); + var payload = (net.firedevops.firemud.gamesession.presentation.NoticeOutput) notice.payload(); + assertThat(payload.arguments()).containsEntry("worldName", displaySelection); + var renderer = new TextPlayerOutputRenderer(new PresentationProperties()); + assertThat(renderer.render(notice, "en-NZ")).isEqualTo(notice.text()); + assertThat(renderer.render(notice, "fr")) + .isEqualTo("Entree dans le monde : " + displaySelection + suffix); + } + @Test void playComposesSelectionCardinalityAndSuccessFromOneActualPointerList() { var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e224892db3..432ca8d988 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -128,6 +128,49 @@ void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); } + @Test + void textWorldOrdinalsAreRefusedEvenWhenMatchingSlugsExistWithoutReadingFreshCatalog() { + gameplayCatalogProperties.setWorlds( + List.of(world("1", 22L, 1L, false), world("123", 23L, 2L, false))); + var original = + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties).visibleWorlds(); + AtomicInteger reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + reads.incrementAndGet(); + return original; + }); + var localHandler = new WorldsCommandHandler(catalog); + var actor = GameplayCommandTestFixtures.worldBrowseDemo(); + + for (String selector : List.of("1", " 123 ", "2")) { + assertThat(localHandler.browseRealms(selector)).isEmpty(); + assertThat(localHandler.browseCharacters(actor, selector, null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + } + assertThat(reads).hasValue(0); + } + + @Test + void charsRefusesUnboundNumericRealmEvenWhenExactRealmSlugExists() { + var demo = world("demo", 22L, 1L, false); + demo.getRealms().getFirst().setSlug("1"); + gameplayCatalogProperties.setWorlds(List.of(demo)); + var original = + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties).visibleWorlds(); + AtomicInteger reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> reads.getAndIncrement() == 0 ? original : List.of()); + + assertThat( + new WorldsCommandHandler(catalog) + .browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", "1")) + .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); + assertThat(reads).hasValue(1); + } + @Test void charsRejectsNonCanonicalCallerBeforeCatalogSelection() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index d5e0d2e6c0..c96852b557 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1366,6 +1366,33 @@ void malformedWorldSelectorRemainsInvalidArgument() { assertEquals(0, response.getRealmsCount()); } + @Test + void typedNumericSlugsResolveInRealmAndPointerApisWithoutFreshListIndexing() { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + var selected = authorityPointer("123", "456", 7L, 44L, true, true); + // A second read within either response would lose the selected target. + Mockito.when(authority.listPointers()).thenReturn(List.of(selected), List.of()); + Mockito.when(authority.listPointersByTenant(7L)).thenReturn(List.of(selected), List.of()); + var service = catalogService(authority); + + var realms = listGameplayRealms(service, "123"); + assertEquals("", realms.getError().getCode()); + assertEquals(1, realms.getRealmsCount()); + assertEquals("456", realms.getRealms(0).getRealmSlug()); + + var pointer = admissionPointer(service, "123", "456"); + assertFalse(pointer.hasError()); + assertEquals("123", pointer.getAdmissionPointer().getWorldSlug()); + assertEquals("456", pointer.getAdmissionPointer().getRealmSlug()); + assertEquals("44", pointer.getAdmissionPointer().getGameInstanceId()); + assertEquals(selected.realmId().toString(), pointer.getAdmissionPointer().getRealmId()); + assertEquals(selected.catalogRevision(), pointer.getAdmissionPointer().getCatalogRevision()); + Mockito.verify(authority).listPointers(); + Mockito.verify(authority).listPointersByTenant(7L); + Mockito.verify(authority, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + @Test void listGameplayRealmsTrimsWorldSelectorBeforeAuthorityResolution() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = From c1f2e86d5ab80f94ed965904b2367765f514311d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:32:20 +1300 Subject: [PATCH 14/23] Use exact lobby slugs without unsupported menu ordinals --- .../game-session-service/protocols.md | 4 +- .../game-session-service/runtime-and-data.md | 4 +- ...r-experience-commands-and-communication.md | 4 +- .../realm-routing-and-playable-state.md | 2 +- .../command/text/GameplayWorldCatalog.java | 11 +- .../command/text/PlayCommandHandler.java | 16 +- .../command/text/WorldsCommandHandler.java | 9 -- .../presentation/RealmBrowseViewOutput.java | 4 - .../TextPlayerOutputRenderer.java | 6 +- .../presentation/WorldsViewOutput.java | 9 +- .../gamesession/service/SessionContext.java | 9 +- .../command/text/PlayCommandHandlerTest.java | 140 +++++++++++++++--- .../text/TextCommandInterpreterTest.java | 5 +- .../text/WorldsCommandHandlerTest.java | 49 ++++-- .../WorldsTextCommandDispatchHandlerTest.java | 34 ++++- .../presentation/PlayerOutputTest.java | 2 +- .../TextPlayerOutputRendererTest.java | 41 ++++- .../presentation/WorldsViewOutputTest.java | 16 +- .../WebSocketOutputProjectorTest.java | 46 ++++++ 19 files changed, 311 insertions(+), 100 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index b22a33de12..9d6c77f79f 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -14,7 +14,7 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, and explicit `JOIN` remains unavailable, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance fails closed with `AUTH_UNAVAILABLE` before replay or admission-authority reads. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; Account already emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but this consumer does not enforce them and therefore does not classify `ACTIVE` or `INACTIVE`. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. -Current catalog receiving remains partial. Direct-text handlers reject unbound numeric world and realm menu selectors instead of interpreting them as positions in the latest list; typed catalog and admission APIs resolve exact canonical slugs, including numeric-only slugs. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. +Current catalog receiving remains partial. Current direct-text world/realm presentation advertises stable slugs only, and text, typed catalog and admission APIs resolve exact canonical slugs, including numeric-only slugs. They do not advertise or interpret unsupported world/realm menu positions. The local direct-text UUID selection store is a separate, unregistered component and does not yet provide the complete target snapshot-bound selector flow or protected receiving custody. Current public/caller-free realm snapshots expose only public-production realms; authenticated private-realm discovery and retained scope are not available. See [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status) and [Game Session Runtime and Data](./runtime-and-data.md#implementation-status) for local implementation and proof status. The target selector rules below remain authoritative. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current direct-text handling refuses unbound numeric world and realm menu selectors because transport-local menu retention is not wired into that flow. Exact typed slug readers do not reinterpret numeric slugs as menu positions. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. ### JOIN Translation and Status diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5c0cba1ece..46d01e8386 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -34,7 +34,7 @@ The sections below define the target-state runtime contract. Current implementat - **Direct-text WORLDS menu retention:** the manually composed menu store and one-key Redis script retain only the public `WORLDS` UI snapshot under the tenantless proxy-UUID family. The numeric transport session ID and the exact observed proxy UUID remain separate correlation values; neither an observed UUID nor Redis `ACL WHOAMI` establishes authenticated receiving custody or LOGIN/JOIN authority. Missing, expired, reset, or source-stale menu state requires a fresh `WORLDS` request and cannot recreate or clear authentication state. Production protected-connection binding, receiving-chain provenance and hidden rebind remain gaps; the source has no deployed ACL change. Focused component and physical Redis proof is recorded in the owning tracker, without establishing genuine receiving custody or registration. See [the Redis menu contract](../../system-architecture-redis.md#direct-text-worlds-ui-menu) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). -- **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while direct-text unbound numeric menu selectors and ambiguous private defaults are refused. Exact typed slug reads accept canonical numeric-only slugs without fresh-list indexing. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). +- **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while ambiguous private defaults are refused. Current world/realm text presentation and selection are exact-slug-only, including canonical numeric-only slugs; unsupported menu positions are neither advertised nor interpreted. Typed APIs also use exact slugs without fresh-list indexing. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. @@ -63,7 +63,7 @@ The sections below define the target-state runtime contract. Current implementat - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. - Current Redis session-context and movement writers persist a projection without the raw `game-session-account-delegation` JWT, preserving other binding fields. Canonical/index and movement legacy reads return the same non-secret projection without rewriting retained values or extending their lifetime. Existing stored bytes are not globally erased: owner-fenced retained-value cleanup, complete rotation/rebind metadata and the rest of [ADR 0031](../../decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) remain incomplete. Focused receiving proof and limits are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#session-secret-and-presence-containment). - An unregistered initial-LOGIN journal, cleanup owner and exact-context Redis CAS/closure adapter are prepared independently of that legacy handler. The adapter follows the [initial-context owner](../../system-architecture-redis.md#initial-login-context-aggregate) and requires the separately supplied protected binding and external qualification; it does not implement legacy Redis context save/delete, trusted TCP custody or runtime LOGIN. Qualified source and physical proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). -- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. +- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and durable logout invalidation remain implementation/proof gaps. Current reconnect suppresses private-context presentation without deleting retained rows; bounded receiving proof and the remaining episode/generation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#reconnect-and-continuity). - Current live-presence registration, returned legacy projections and ordinary activity updates use `PLAYER`: no independently verified gameplay-grant carrier is available. JWT global/scoped roles and retained cached elevation grant no gameplay capability. Read projection does not persist the demotion or refresh TTL; ordinary activity writes retain their existing lifetime behavior and preserve other fields. The [authentication owner](../../system-architecture-authentication.md#global-role-to-route-class-matrix-normative) defines grant authority; [Player Experience](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#communication-social-and-presence) records implementation/proof limits. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 333d020bb7..4d02d7e2be 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -23,7 +23,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm catalog and admission pointers](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | | EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; current reconnect suppresses private-context presentation and current first-party LOGIN/PLAY deny; durable episode/generation-qualified replay and logout invalidation remain unproved. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; current reconnect suppresses private-context presentation and current first-party LOGIN/PLAY deny; durable episode/generation-qualified replay and logout invalidation remain unproved. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output. Current WebSocket reconnect suppresses retained private-context presentation and first-party `LOGIN`/`PLAY` deny before legacy effects; durable `LOGOUT` invalidation and episode/generation-qualified replay remain unproved. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | | EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - previously recorded focused evidence remains attributed to its original sources; R1423 qualifies PLAYER-only creation/projection, cached-role read projection without persisting demotion or extending presence TTL, and ordinary field-preserving updates. Snapshot-bound pagination, current friendship/block revalidation, bounded-page proof, and production tenant-gameplay-grant qualification also remain incomplete. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [RedisGameplayPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java); [RedisAccountRecentPresenceService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java); [AccountClient.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/client/AccountClient.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [WhoCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java); [RedisAccountRecentPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java); [AccountClientTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Current Game Session has no independently verified gameplay-grant carrier, so new and returned presence uses `PLAYER`; JWT global/scoped claims and retained elevated cache roles do not elevate a presence projection. Read-side role demotion is projection-only and does not persist the role change or extend presence TTL; ordinary activity updates persist `PLAYER` while preserving the other presence fields. R1423 qualifies this bounded behavior through the Redis, WHO/reconnect units and real-Redis cases described below. Complete snapshot-bound pagination, current relationship/block revalidation, bounded-page proof, production tenant-gameplay-grant qualification, and broader authorization/disclosure proof remain open. Keep in-world concealment under gameplay policy before calling this capability proven. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | @@ -52,7 +52,7 @@ This section records implementation and proof status only. The target command, p Current text `WORLDS` remains an optional pre-login public browse and authenticated `REALMS` discovery remains supported. Direct-text `CHARS` currently returns unavailable without calling Entity's legacy roster adapter; the supported Account bootstrap/HTTP character roster is separate. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing; any known-character selector guidance identifies a selection only and does not establish membership or public admission. For existing members, `LOGIN` followed by an unambiguous eligible `PLAY [character]` remains the direct gameplay-binding path. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance instead validates bootstrap identity and retained scope, then fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay, or token work; [Account runtime status](../../architecture/microservices/account-service/runtime-and-data.md) owns that current behavior. Target membership-authority-generation rereads and successful issuance remain gaps. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. Ambiguous or inaccessible `PLAY` selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also refuses unbound numeric menu selectors at text entry boundaries while typed APIs resolve exact canonical numeric-only slugs and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior remains bounded current behavior; Account connect-token issuance remains unavailable before membership or policy evaluation. R1424 qualifies bounded HELP/PLAY and WebSocket containment, not successful issuance or target admission ordering. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The current admission gaps are explicit `JOIN`, the unavailable direct-text `CHARS` boundary, and the connect-token membership-authority-generation reread. The supported Account bootstrap/HTTP roster is separate and does not complete text-command actor discovery. The local #2857 receiving change also uses exact stable slug-only text and typed selection, including canonical numeric-only slugs, without advertising or interpreting unsupported menu ordinals and uses one catalog snapshot for composed `PLAY`/`WORLDS` decisions, with focused R1430 proof recorded in the linked tracker; the separate exact-target UUID menu store is unregistered, and authenticated private `REALMS`, protected receiving, and `JOIN` remain held. See [Realm Routing and Playable State](./realm-routing-and-playable-state.md#capability-status) for the bounded behavior and proof status. The `PLAY`-side `JOIN_REQUIRED` behavior remains bounded current behavior; Account connect-token issuance remains unavailable before membership or policy evaluation. R1424 qualifies bounded HELP/PLAY and WebSocket containment, not successful issuance or target admission ordering. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index c6ddb18f22..f4a2f2116e 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -51,7 +51,7 @@ The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer a `GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. It groups rows by `{tenantId, worldSlug, realmSlug}` and emits a visible catalog entry only for exactly one complete row in that tenant-qualified selector scope. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target; duplicate selector rows within a tenant, duplicate runtime matches, and incomplete rows disappear from player-facing catalog projection rather than selecting an arbitrary row. -The current local #2857 receiver correction keeps the catalog-side boundary fail-closed: unbound numeric menu selectors are refused at text entry boundaries, exact typed slug reads accept canonical numeric-only world/realm slugs without indexing a fresh list, and composed `PLAY`/`WORLDS` decisions use one immutable catalog snapshot. Public/caller-free realm snapshots contain only public-production realms, private-only defaults are not inferred when ambiguous, and `GetAdmissionPointer` validates the selected slug tuple against one actual tenant pointer-list response. This does not wire in the separate exact-target direct-text UUID menu store or establish complete canonical `tenantSlug/worldSlug` support; authenticated private `REALMS` retention, protected receiving, explicit `JOIN`, and first-party admission remain gaps. R1430 passes 293 selected command/catalog/gRPC unit cases and 11 actual PostgreSQL migration cases, with no failures, errors or skips, plus canonical jOOQ generation and enabled service static/format checks. The initial migration test compilation failure was corrected before the separate physical run; the retained unit result and successful migration result are distinct runs. `AA-3.1`/`AA-3.3` remain partial and `drift-found` because the complete target is still absent. V1053 adds only a forward partial unique guard for visible public-production pointer cardinality per tenant; zero remains physically representable and is rejected by current readers, while the current realm catalog and V12/V13 are unchanged. The two new PostgreSQL cases prove successful existing-data migration, unchanged retained rows/events and migration history, rejection of duplicate visible public-production rows, and atomic refusal for pre-existing duplicate authority; nine existing pointer-migration cases also pass. +The current local #2857 receiver correction keeps the catalog-side boundary fail-closed: current world/realm text presentation and selection use exact stable slugs only, including canonical numeric-only slugs, without advertising or interpreting unsupported menu positions; typed APIs likewise never index a fresh list, and composed `PLAY`/`WORLDS` decisions use one immutable catalog snapshot. Public/caller-free realm snapshots contain only public-production realms, private-only defaults are not inferred when ambiguous, and `GetAdmissionPointer` validates the selected slug tuple against one actual tenant pointer-list response. This does not wire in the separate exact-target direct-text UUID menu store or establish complete canonical `tenantSlug/worldSlug` support; authenticated private `REALMS` retention, protected receiving, explicit `JOIN`, and first-party admission remain gaps. R1430 passes 293 selected command/catalog/gRPC unit cases and 11 actual PostgreSQL migration cases, with no failures, errors or skips, plus canonical jOOQ generation and enabled service static/format checks. The initial migration test compilation failure was corrected before the separate physical run; the retained unit result and successful migration result are distinct runs. `AA-3.1`/`AA-3.3` remain partial and `drift-found` because the complete target is still absent. V1053 adds only a forward partial unique guard for visible public-production pointer cardinality per tenant; zero remains physically representable and is rejected by current readers, while the current realm catalog and V12/V13 are unchanged. The two new PostgreSQL cases prove successful existing-data migration, unchanged retained rows/events and migration history, rejection of duplicate visible public-production rows, and atomic refusal for pre-existing duplicate authority; nine existing pointer-migration cases also pass. Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index ee3f9370cb..e640d0387e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -570,7 +570,6 @@ private List worldEntries(List worlds) { RealmView publicRealm = world.realms().getFirst(); entries.add( new WorldsViewOutput.WorldEntry( - entries.size() + 1, world.slug(), world.displayName(), publicRealm.gameInstanceId(), @@ -582,11 +581,9 @@ private List worldEntries(List worlds) { private List realmEntries(WorldView world) { List realms = visibleRealms(world); ArrayList entries = new ArrayList<>(realms.size()); - for (int i = 0; i < realms.size(); i++) { - RealmView realm = realms.get(i); + for (RealmView realm : realms) { entries.add( new RealmBrowseViewOutput.RealmEntry( - i + 1, realm.slug(), realm.displayName(), realm.gameInstanceId(), @@ -936,12 +933,6 @@ private static String selectorKey(String slug) { return slug.trim().toLowerCase(Locale.ROOT); } - static boolean isOrdinalSelector(String selector) { - return selector != null - && !selector.isBlank() - && selector.trim().chars().allMatch(character -> character >= '0' && character <= '9'); - } - private record RealmSelectorKey(long tenantId, String selector) {} private static RealmView copyRealmView(RealmView input) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index f49f5c4ba8..fcd2e0f9af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -251,10 +251,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } Optional maybeRealm = selection.explicitRealmSelector() != null - ? GameplayWorldCatalog.isOrdinalSelector(selection.explicitRealmSelector()) - ? Optional.empty() - : gameplayWorldCatalog.resolveRealmForAdmission( - selectedWorld, selection.explicitRealmSelector()) + ? gameplayWorldCatalog.resolveRealmForAdmission( + selectedWorld, selection.explicitRealmSelector()) : selectDefaultRealm(selectedWorld, catalogSnapshot); if (maybeRealm.isEmpty()) { return failure( @@ -1016,8 +1014,7 @@ private Optional resolveSelection( TextCommandPayload.PlayRequest playRequest, GameplayWorldCatalog.ReadSnapshot catalogSnapshot) { String worldSelector = playRequest.worldSelector(); - if (!StringUtils.hasText(worldSelector) - || GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { + if (!StringUtils.hasText(worldSelector)) { return Optional.empty(); } String secondSelector = @@ -1037,10 +1034,9 @@ private Optional resolveSelection( catalogSnapshot.resolveWorld(worldSelector); if (maybeWorld.isPresent() && StringUtils.hasText(secondSelector) - && (GameplayWorldCatalog.isOrdinalSelector(secondSelector) - || !gameplayWorldCatalog.hasRealmForAdmission( - maybeWorld.orElseThrow(), secondSelector))) { - // A numeric second argument remains a character name, never an unbound realm ordinal. + && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { + // If no exact realm slug matches, the two-argument form treats the selector as a character + // name. Character resolution remains exact and never indexes a fresh roster. return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), null, secondSelector)); } return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index fc622d35af..702b7128be 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -26,9 +26,6 @@ public WorldsViewOutput browseView() { } public java.util.Optional browseRealms(String worldSelector) { - if (GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { - return java.util.Optional.empty(); - } return worldCatalog.browseRealms(worldSelector); } @@ -38,9 +35,6 @@ public CharacterBrowseResult browseCharacters( if (!sessionContext.hasAccountIdentity()) { return CharacterBrowseResult.unavailable(); } - if (GameplayWorldCatalog.isOrdinalSelector(worldSelector)) { - return CharacterBrowseResult.invalidWorld(); - } GameplayWorldCatalog.ReadSnapshot snapshot = worldCatalog.readSnapshot(); java.util.Optional maybeWorld = snapshot.resolveWorld(worldSelector); @@ -48,9 +42,6 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.invalidWorld(); } GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); - if (GameplayWorldCatalog.isOrdinalSelector(realmSelector)) { - return CharacterBrowseResult.invalidRealm(world.slug()); - } java.util.Optional maybeRealm = StringUtils.hasText(realmSelector) ? worldCatalog.resolveRealm(world, realmSelector) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java index aceaec97b7..2b5504f682 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java @@ -12,7 +12,6 @@ public record RealmBrowseViewOutput(String worldSlug, List realms) } public record RealmEntry( - int ordinal, String realmSlug, String displayName, long gameInstanceId, @@ -20,9 +19,6 @@ public record RealmEntry( String stateScope, String characterCreationPolicy) { public RealmEntry { - if (ordinal < 1) { - throw new IllegalArgumentException("ordinal must be at least 1"); - } Objects.requireNonNull(realmSlug, "realmSlug must not be null"); Objects.requireNonNull(displayName, "displayName must not be null"); Objects.requireNonNull(stateScope, "stateScope must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java index 556809873e..0c6bf6e041 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java @@ -355,7 +355,7 @@ private String renderPrompt( private String renderWorldsView(WorldsViewOutput output) { return output.worlds().stream() - .map(world -> world.ordinal() + ") " + world.displayName() + " (" + world.slug() + ")") + .map(world -> world.displayName() + " (" + world.slug() + ")") .collect(Collectors.joining("\n")); } @@ -363,9 +363,7 @@ private String renderRealmsView(RealmBrowseViewOutput output) { return output.realms().stream() .map( realm -> - realm.ordinal() - + ") " - + realm.displayName() + realm.displayName() + " (" + realm.realmSlug() + ") [" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java index bbfe4786cd..55e5e032a2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java @@ -10,15 +10,8 @@ public record WorldsViewOutput(List worlds) implements PlayerOutputP } public record WorldEntry( - int ordinal, - String slug, - String displayName, - long gameInstanceId, - boolean requiresCharacterSelection) { + String slug, String displayName, long gameInstanceId, boolean requiresCharacterSelection) { public WorldEntry { - if (ordinal < 1) { - throw new IllegalArgumentException("ordinal must be at least 1"); - } Objects.requireNonNull(slug, "slug must not be null"); Objects.requireNonNull(displayName, "displayName must not be null"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index 38a26786eb..9fc8509993 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -319,7 +319,14 @@ private static String normalizeText(String text) { return text.trim(); } - /** Returns the non-secret Redis projection without changing this process-local context. */ + /** + * Returns the non-secret Redis projection without changing this immutable input. + * + *

Redis reads return this projection with a null JWT. An incoming context may carry a + * transient credential, but this method neither retains it in a process-local store nor + * reattaches it after a read. Authentication and downstream credentials must not depend on a + * stored context JWT. + */ public SessionContext withoutJwt() { if (jwt == null) { return this; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 91a46a4d6f..b0adc2abd1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -172,10 +172,30 @@ void setUp() { }); } + @Test + void playResolvesAnExactNumericWorldSlugInsteadOfItsListPosition() { + gameplayCatalogProperties.getWorlds().get(1).setSlug("1"); + SessionContext existing = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(existing)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY 1 preview Emberline")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())) + .isEqualTo("Entered world: 1 (preview) as Emberline"); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.worldSlug().equals("1") + && saved.realmSlug().equals("preview") + && saved.gameInstanceId() == 41L + && saved.characterName().equals("Emberline"))); + } + @ParameterizedTest - @ValueSource(strings = {"1", "123", "2"}) - void playRefusesUnboundNumericWorldEvenWhenExactSlugExists(String selector) { - gameplayCatalogProperties.getWorlds().getFirst().setSlug(selector); + @ValueSource(strings = {"1", "2"}) + void playRefusesUnmatchedNumericWorldInsteadOfUsingFreshListPosition(String selector) { SessionContext existing = previewRealmContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(existing)); @@ -195,16 +215,33 @@ void playRefusesUnboundNumericWorldEvenWhenExactSlugExists(String selector) { gameplayPresenceLifecycleService); } - @ParameterizedTest - @ValueSource(strings = {"1", "123"}) - void playRefusesUnboundNumericExplicitRealmEvenWhenExactSlugExists(String selector) { - gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setSlug(selector); - SessionContext existing = previewRealmContext(); - when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(existing)); + @Test + void playResolvesAnExactNumericRealmSlugInsteadOfItsListPosition() { + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setSlug("1"); + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - var result = - handler.handle( - "1", new TextCommandParser().parse("PLAY sandbox " + selector + " Emberline")); + var result = handler.handle("1", new TextCommandParser().parse("PLAY sandbox 1 Emberline")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())) + .isEqualTo("Entered world: sandbox (1) as Emberline"); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.worldSlug().equals("sandbox") + && saved.realmSlug().equals("1") + && saved.gameInstanceId() == 41L + && saved.characterName().equals("Emberline"))); + } + + @Test + void playRefusesUnmatchedNumericRealmInsteadOfUsingFreshListPosition() { + SessionContext context = previewRealmContext(); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY sandbox 1 Emberline")); assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); @@ -223,13 +260,7 @@ void playRefusesUnboundNumericExplicitRealmEvenWhenExactSlugExists(String select @ParameterizedTest @ValueSource(strings = {"PLAY demo 1", "PLAY demo production 1"}) - void numericCharacterNameStillResolvesExactlyEvenWhenANumericRealmExists(String command) { - // A hidden numeric realm is available to admission lookup but must not steal a character name. - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .add(realm("1", "Hidden Realm", 22L, 41L, false, true)); + void numericCharacterSelectorResolvesItsExactNameWithoutRosterIndexing(String command) { SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -260,6 +291,77 @@ void numericCharacterNameStillResolvesExactlyEvenWhenANumericRealmExists(String Mockito.anyString()); } + @Test + void twoArgumentNumericSelectorPrefersAnExactKnownRealmSlug() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .add(realm("1", "Hidden Realm", 22L, 41L, false, false)); + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", ACCOUNT_ID, "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7002", + "Realm Actor", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo 1")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())) + .isEqualTo("Entered world: demo (1) as Realm Actor"); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.gameInstanceId() == 41L + && saved.realmSlug().equals("1") + && saved.characterName().equals("Realm Actor"))); + Mockito.verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq(ACCOUNT_ID), + Mockito.eq("22"), + Mockito.eq("demo"), + Mockito.eq("1"), + Mockito.anyString()); + } + + @Test + void explicitRealmKeepsNumericCharacterNameUnambiguousWhenSameNumericRealmExists() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .add(realm("1", "Numeric Realm", 22L, 41L, false, false)); + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "1", "22", ACCOUNT_ID, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo production 1")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as 1"); + Mockito.verify(sessionContextService) + .save( + Mockito.argThat( + saved -> + saved.gameInstanceId() == 1L + && saved.realmSlug().equals("production") + && saved.characterId() == 7001L + && saved.characterName().equals("1"))); + } + @ParameterizedTest @ValueSource(strings = {"PLAY demo 1", "PLAY demo production 1"}) void numericCharacterSelectorNeverIndexesAFreshRoster(String command) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 75666c49f2..d8a1b995da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -517,8 +517,9 @@ void worldsAreVisibleBeforeLogin() { assertEquals( List.of(PlayerOutputKind.VIEW), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertTrue(renderedResponse("WORLDS", interpretation).startsWith("OK WORLDS\n1) Demo World")); - assertTrue(renderedResponse("WORLDS", interpretation).contains("Demo World")); + String rendered = renderedResponse("WORLDS", interpretation); + assertTrue(rendered.startsWith("OK WORLDS\nDemo World (demo)")); + assertFalse(rendered.contains("\n1) ")); verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 432ca8d988..e44aa7d3a2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -129,9 +129,11 @@ void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { } @Test - void textWorldOrdinalsAreRefusedEvenWhenMatchingSlugsExistWithoutReadingFreshCatalog() { - gameplayCatalogProperties.setWorlds( - List.of(world("1", 22L, 1L, false), world("123", 23L, 2L, false))); + void numericWorldAndRealmSelectorsResolveExactSlugsWithoutOrdinalFallback() { + GameplayCatalogProperties.World otherWorld = world("other", 23L, 1L, false); + GameplayCatalogProperties.World numericWorld = world("1", 22L, 2L, false); + numericWorld.getRealms().getFirst().setSlug("2"); + gameplayCatalogProperties.setWorlds(List.of(otherWorld, numericWorld)); var original = TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties).visibleWorlds(); AtomicInteger reads = new AtomicInteger(); @@ -144,16 +146,22 @@ void textWorldOrdinalsAreRefusedEvenWhenMatchingSlugsExistWithoutReadingFreshCat var localHandler = new WorldsCommandHandler(catalog); var actor = GameplayCommandTestFixtures.worldBrowseDemo(); - for (String selector : List.of("1", " 123 ", "2")) { - assertThat(localHandler.browseRealms(selector)).isEmpty(); - assertThat(localHandler.browseCharacters(actor, selector, null)) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); - } - assertThat(reads).hasValue(0); + RealmBrowseViewOutput realms = localHandler.browseRealms("1").orElseThrow(); + + assertThat(realms.worldSlug()).isEqualTo("1"); + assertThat(realms.realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("2"); + assertThat(localHandler.browseCharacters(actor, "1", "2")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + assertThat(localHandler.browseRealms("2")).isEmpty(); + assertThat(localHandler.browseCharacters(actor, "2", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + assertThat(reads).hasValue(4); } @Test - void charsRefusesUnboundNumericRealmEvenWhenExactRealmSlugExists() { + void charsAcceptsAnExactNumericRealmSlug() { var demo = world("demo", 22L, 1L, false); demo.getRealms().getFirst().setSlug("1"); gameplayCatalogProperties.setWorlds(List.of(demo)); @@ -167,10 +175,29 @@ void charsRefusesUnboundNumericRealmEvenWhenExactRealmSlugExists() { assertThat( new WorldsCommandHandler(catalog) .browseCharacters(GameplayCommandTestFixtures.worldBrowseDemo(), "demo", "1")) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.InvalidRealm("demo")); + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); assertThat(reads).hasValue(1); } + @Test + void numericCharacterBrowseSelectorStillRequiresCanonicalAccountIdentity() { + AtomicInteger reads = new AtomicInteger(); + var catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + reads.incrementAndGet(); + return List.of(new GameplayWorldCatalog.WorldView("123", "Numeric World", List.of())); + }); + var invalidAccountContext = + new net.firedevops.firemud.gamesession.service.SessionContext( + 1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"); + + assertThat( + new WorldsCommandHandler(catalog).browseCharacters(invalidAccountContext, "123", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + assertThat(reads).hasValue(0); + } + @Test void charsRejectsNonCanonicalCallerBeforeCatalogSelection() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index d811bf9af7..a330b7b62f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -50,7 +50,7 @@ void preparedJoinExplicitlyRefusesWithoutDiscoveryOrGameplayEffects() { } @Test - void unboundWorldOrdinalReturnsRediscoveryGuidanceWithoutPublishingAnEvent() { + void nonmatchingNumericWorldSelectorReturnsRediscoveryGuidanceWithoutPublishingAnEvent() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); var result = handler.handle( @@ -73,6 +73,38 @@ void unboundWorldOrdinalReturnsRediscoveryGuidanceWithoutPublishingAnEvent() { Mockito.verifyNoInteractions(scriptEventPublisher); } + @Test + void dispatchAcceptsExactNumericWorldSlugWithoutTreatingItAsAListPosition() { + gameplayCatalogProperties.setWorlds( + List.of(world("other", 23L, 40L, false), world("1", 22L, 41L, false))); + SessionContext context = GameplayCommandTestFixtures.authoredDispatchEmberline(); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + new TextCommandParser().parse("REALMS 1"), + false, + Optional.of(context), + Optional.empty())); + + assertThat(result.commandResult().accepted()).isTrue(); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.payload()).isInstanceOf(RealmBrowseViewOutput.class); + assertThat(((RealmBrowseViewOutput) output.payload()).worldSlug()).isEqualTo("1"); + }); + Mockito.verify(scriptEventPublisher) + .publishCommandEvent( + Mockito.eq(context), + Mockito.argThat( + gameplayCommand -> + "REALMS".equals(gameplayCommand.getCommandName()) + && "REALMS 1".equals(gameplayCommand.getCommandText()))); + } + @Test void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = GameplayCommandTestFixtures.authoredDispatchEmberline(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java index 29f1a4a443..45fd151b20 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java @@ -33,7 +33,7 @@ void screenBufferEligibilityFollowsReplayPolicyAndOutputKind() { PlayerOutput.view( new WorldsViewOutput( java.util.List.of( - new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false)))) + new WorldsViewOutput.WorldEntry("demo", "Demo World", 1L, false)))) .screenBufferEligible()) .isFalse(); assertThat(PlayerOutput.prompt("demo> ").screenBufferEligible()).isFalse(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index bfc366cd06..9ee01c0fb5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -1043,10 +1043,9 @@ void renderAllFormatsMultilineNoticeAsCommandBody() { renderer.renderAll( new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), CommandEnqueueResult.success(), - List.of(PlayerOutput.notice("1) Demo World (demo)\n2) Builder Sandbox (sandbox)"))); + List.of(PlayerOutput.notice("Demo World (demo)\nBuilder Sandbox (sandbox)"))); - assertThat(rendered) - .isEqualTo("OK WORLDS\n1) Demo World (demo)\n2) Builder Sandbox (sandbox)\n\n"); + assertThat(rendered).isEqualTo("OK WORLDS\nDemo World (demo)\nBuilder Sandbox (sandbox)\n\n"); } @Test @@ -1067,12 +1066,40 @@ void renderAllFormatsWorldsViewAsCommandBody() { PlayerOutput.view( new WorldsViewOutput( List.of( - new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false), - new WorldsViewOutput.WorldEntry( - 2, "sandbox", "Builder Sandbox", 2L, true)))))); + new WorldsViewOutput.WorldEntry("demo", "Demo World", 1L, false), + new WorldsViewOutput.WorldEntry("123", "Numeric World", 2L, true)))))); + + assertThat(rendered).isEqualTo("OK WORLDS\nDemo World (demo)\nNumeric World (123)\n\n"); + } + + @Test + void renderAllFormatsRealmsViewWithStableSlugSelectorsOnly() { + TextPlayerOutputRenderer renderer = + new TextPlayerOutputRenderer( + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(false, true, 150L))); + + String rendered = + renderer.renderAll( + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo"), + CommandEnqueueResult.success(), + List.of( + PlayerOutput.view( + new RealmBrowseViewOutput( + "demo", + List.of( + new RealmBrowseViewOutput.RealmEntry( + "123", "Numeric Realm", 1L, false, "SHARED", "ALLOW_NEW"), + new RealmBrowseViewOutput.RealmEntry( + "production", "Live Realm", 2L, true, "ISOLATED", "PRESEEDED")))))); assertThat(rendered) - .isEqualTo("OK WORLDS\n1) Demo World (demo)\n2) Builder Sandbox (sandbox)\n\n"); + .isEqualTo( + "OK REALMS\nNumeric Realm (123) [shared, allow_new]\n" + + "Live Realm (production) [isolated, preseeded]\n\n"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java index 7e3bdd2e97..2148f7aa64 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java @@ -1,8 +1,9 @@ package net.firedevops.firemud.gamesession.presentation; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.lang.reflect.RecordComponent; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -11,18 +12,21 @@ class WorldsViewOutputTest { void worldsAreCopiedDefensively() { List worlds = new java.util.ArrayList<>( - List.of(new WorldsViewOutput.WorldEntry(1, "demo", "Demo World", 1L, false))); + List.of(new WorldsViewOutput.WorldEntry("123", "Demo World", 1L, false))); WorldsViewOutput output = new WorldsViewOutput(worlds); worlds.clear(); assertThat(output.worlds()).hasSize(1); + assertThat(output.worlds().getFirst().slug()).isEqualTo("123"); } @Test - void ordinalMustBePositive() { - assertThatThrownBy(() -> new WorldsViewOutput.WorldEntry(0, "demo", "Demo World", 1L, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("ordinal"); + void worldEntryCarriesNoListOrdinal() { + assertThat( + Arrays.stream(WorldsViewOutput.WorldEntry.class.getRecordComponents()) + .map(RecordComponent::getName) + .toList()) + .containsExactly("slug", "displayName", "gameInstanceId", "requiresCharacterSelection"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 12c5beaf73..907c2f00c3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -30,8 +30,10 @@ import net.firedevops.firemud.gamesession.presentation.ItemMutationResultOutput; import net.firedevops.firemud.gamesession.presentation.LookViewOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WhoViewOutput; +import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; import org.junit.jupiter.api.Test; @@ -221,6 +223,50 @@ void firstPartyWebReceivesStructuredAsyncOutputEnvelope() throws Exception { .isEqualTo("communication.whisper.actor"); } + @Test + void firstPartyLobbyViewsExposeStableSlugsWithoutListOrdinals() throws Exception { + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); + + String worldsPayload = + projector.projectPlayerOutput( + session, + PlayerOutput.view( + new WorldsViewOutput( + List.of(new WorldsViewOutput.WorldEntry("123", "Numeric World", 41L, false)))), + "en-NZ", + presentation); + JsonNode worlds = objectMapper.readTree(worldsPayload); + JsonNode world = worlds.path("outputs").get(0).path("payload").path("worlds").get(0); + + assertThat(worlds.path("outputs").get(0).path("payloadType").asText()).isEqualTo("worlds_view"); + assertThat(world.path("slug").asText()).isEqualTo("123"); + assertThat(world.has("ordinal")).isFalse(); + + String realmsPayload = + projector.projectPlayerOutput( + session, + PlayerOutput.view( + new RealmBrowseViewOutput( + "123", + List.of( + new RealmBrowseViewOutput.RealmEntry( + "456", "Numeric Realm", 41L, false, "SHARED", "ALLOW_NEW")))), + "en-NZ", + presentation); + JsonNode realms = objectMapper.readTree(realmsPayload); + JsonNode realm = realms.path("outputs").get(0).path("payload").path("realms").get(0); + + assertThat(realms.path("outputs").get(0).path("payloadType").asText()).isEqualTo("realms_view"); + assertThat(realms.path("outputs").get(0).path("payload").path("worldSlug").asText()) + .isEqualTo("123"); + assertThat(realm.path("realmSlug").asText()).isEqualTo("456"); + assertThat(realm.has("ordinal")).isFalse(); + } + @Test void genericWebSocketProjectsViewOutputThroughLookRenderer() { TextPlayerOutputRenderer renderer = mock(TextPlayerOutputRenderer.class); From ebb006e964bd4139b02cbe336c21dac0040a4158 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:48:49 +1300 Subject: [PATCH 15/23] Use a distinct canonical UUID in movement identity conflict proof --- .../RedisMovementEffectIdempotencyServiceTest.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index c7db98e6f8..65da7b5e0b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -2,8 +2,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; @@ -96,7 +98,12 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { SessionContext current = baselineContext(); when(valueOperations.get("sessionctx:22:41:context")).thenReturn(current); when(valueOperations.get("sessionctx:22:41:movement-effect:tfx-1")).thenReturn(null); - MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); + SessionContext differentAccount = + withAccountId(current, "2b23537d-c5cc-4fa8-8c0d-dc4c38c77a92"); + assertTrue(current.hasAccountIdentity()); + assertTrue(differentAccount.hasAccountIdentity()); + assertNotEquals(current.accountId(), differentAccount.accountId()); + MoveEffectApplyResult result = service.apply("tfx-1", differentAccount, "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); assertEquals(current.withoutJwt(), result.context()); @@ -194,11 +201,11 @@ private SessionContext baselineContext() { "SHARED"); } - private SessionContext withAccountId(SessionContext context, long accountId) { + private SessionContext withAccountId(SessionContext context, String accountId) { return new SessionContext( context.sessionId(), context.tenantId(), - Long.toString(accountId), + accountId, context.loginName(), context.characterId(), context.characterName(), From 396418466f0d43ab1f842a23307446bd09c27bb4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:07:24 +1300 Subject: [PATCH 16/23] Handle admission pointer conflicts and align smoke discovery with exact slugs --- .../game-session-service/operations.md | 15 ++ .../tcp-proxy-service/api-contracts.md | 4 +- dev-tools/smoke/smoke_common.py | 17 +- dev-tools/tests/smoke-transport-contract.sh | 42 +++-- .../GameplayAdmissionPointerRepository.java | 24 ++- .../AdmissionPointerConflictException.java | 11 ++ ...sionPointerCardinalityIntegrationTest.java | 146 ++++++++++++++++++ ...ameplayAdmissionPointerRepositoryTest.java | 88 +++++++++++ ...yAdmissionPointerAuthorityServiceTest.java | 39 +++++ 9 files changed, 362 insertions(+), 24 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java diff --git a/design/architecture/microservices/game-session-service/operations.md b/design/architecture/microservices/game-session-service/operations.md index 070ac35f94..a9d1ba69cb 100644 --- a/design/architecture/microservices/game-session-service/operations.md +++ b/design/architecture/microservices/game-session-service/operations.md @@ -47,6 +47,21 @@ Before deploying the new Game Session admission validation, Automation must alre - Prometheus scrapes metrics from `/actuator/prometheus`. - Target state: logs, traces, and control-plane reads expose the active exact `{scriptPatchVersion, scriptPinEpoch}` execution fence so operators can identify the hotfix revision and selection epoch during incident triage without adding either raw value as ordinary high-cardinality metric labels. Current coverage is summarized in [Implementation Status](#implementation-status). +### Visible public-production pointer cardinality preflight + +Before applying the existing V1053 cardinality migration, run this read-only query against the deployed Game Session schema: + +```sql +SELECT tenant_id, COUNT(*) AS visible_public_production_pointer_count +FROM gameplay_admission_pointer +WHERE visible = true AND public_production_realm = true +GROUP BY tenant_id +HAVING COUNT(*) > 1 +ORDER BY tenant_id; +``` + +Any returned tenant blocks the migration until the Game Session data owner performs an owner-scoped, audited resolution that preserves pointer rows, audit events, and retained history. Never choose a winner, delete rows, or reset pointer state automatically. A separate-row switch must hide or demote the existing qualifying row before making its replacement qualifying, within the authorized owner's existing atomic/fenced transaction; this is not an ad hoc SQL/operator mutation path. The current `SetAdmissionPointer` and prepared-cutover mutation paths remain held, not implemented. Multi-Tenancy owns the [canonical realm-catalog and admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); the [Realm Routing and Playable State tracker](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status) records the current pointer and cutover status. + ### Initial region timeline recovery boundary For an initial region timeline whose durable preparation is `INITIALIZING` after its one-time creation permission was consumed, absent Redis metadata cannot distinguish never-executed initialization from metadata loss. Descriptor, source, connection, principal, `SCRIPT LOAD`, or current-binding/World/incarnation revalidation refusal before the SQL claim does not change the preparation phase or timeline keys. If the preparation is still `PREPARED` and the proved-absent preimage remains valid, a corrected ordinary attempt can still make the first claim; an existing `INITIALIZING` phase remains held. After those checks pass, the owner claims the permission and immediately attempts the sole `EVALSHA`; a process stop between claim and send or an ambiguous send/result leaves the scope held, with no automatic same-scope retry or recovery. Preserve the original SQL preparation and source evidence. Do not delete or reset the affected region keys, recreate metadata, or retry with a fresh create permission or same-epoch rewrite. No same-scope automated or operator repair exists. Stop and quarantine the affected admission scope; use World Management's normal authorized [instance termination lifecycle](../world-management-service/api-contracts.md#instance-termination-contract) and proceed under a new instance scope only when its usual authorization and protection are available. Otherwise keep the scope blocked for owner-scoped reconciliation. This is a safe recovery boundary, not an implemented or proved repair procedure, and does not qualify launch, production activation, or first `OPEN`. Region timeline and lease authority remain with [Tick System](../../system-architecture-ticks.md#region-authority-and-tick-executor), Redis owns the [key projection](../../system-architecture-redis.md#canonical-region-key-projection), and current Game Session recovery gaps are tracked in [runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). diff --git a/design/architecture/microservices/tcp-proxy-service/api-contracts.md b/design/architecture/microservices/tcp-proxy-service/api-contracts.md index 44e4346046..6b6eda8337 100644 --- a/design/architecture/microservices/tcp-proxy-service/api-contracts.md +++ b/design/architecture/microservices/tcp-proxy-service/api-contracts.md @@ -12,9 +12,9 @@ Current proxy routing and receiving-service behavior support an abbreviated retu The proxy does not expose a public client API. Instead it emits a gRPC event for internal coordination: -- **NotifyDisconnect** – informs the Game Session Service when a Telnet client drops so the session may be suspended. This exists primarily to provide a fast, correlatable liveness hint keyed by `proxyConnectionId` when Telnet sockets close, even if the proxy’s WebSocket bridge teardown or downstream close detection is delayed or ambiguous during restarts. +- **NotifyDisconnect** – a best-effort, at-least-once advisory liveness hint keyed by `{proxyConnectionId, disconnectSequence}`. It can help correlate a Telnet socket closure but does not suspend or resume a gameplay session or resume command queues. The current Game Session receiver performs bounded, read-only metadata checks and acknowledges without shared suspension or presence effects. -These events let the Game Session Service resume suspended sessions and resume processing of any Redis-backed gameplay command queues it owns. They do not authorize replay of prior outbound transport bytes onto a new client socket. The TCP Proxy never replays Telnet input after a disconnect; connection-local buffers are cleared as soon as the TCP session closes. `NotifyDisconnect` is therefore a best-effort, at-least-once lifecycle signal keyed by `{proxyConnectionId, disconnectSequence}` rather than a request to re-run gameplay commands. +Actual current cleanup follows the exact-owned WebSocket close path; when its established Proxy-to-Gateway bridge is lost, the TCP Proxy closes the corresponding Telnet socket. `NotifyDisconnect` neither substitutes for that closure nor authorizes replay of client input or prior outbound frames, bytes, or MCP traffic. The TCP Proxy never replays Telnet input, and connection-local buffers are cleared when the TCP socket closes. Namespace/controller fencing remains a proof gap under [ADR 0132](../../decisions/adr-0132-namespace-scoped-single-character-controller.md); the existing bounded retry limits below are unchanged. The proxy is an edge component, not the owner of resumable gameplay state or external close translation. One live Telnet socket owns one established inbound TCP Proxy -> Gateway WebSocket bridge. Under [ADR 0013](../../decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md), Gateway may retain that inbound bridge while replacing or rebinding its distinct outbound Gateway -> Game Session connection; successful bounded rebind is invisible to the Telnet client. If the TCP Proxy -> Gateway bridge itself drops after establishment, the proxy closes the live Telnet socket and never opens a replacement bridge behind it. The proxy preserves no authoritative gameplay state for Gateway's upstream recovery. If safe backend recovery cannot complete within the configured positive `firemud.gateway.backendUnavailableGraceMs` grace window, capped at 30,000 ms, Gateway closes with `backend_unavailable` and the proxy surfaces the corresponding explicit Telnet disconnect rather than keeping an indefinitely stalled TCP session. No input, frame, byte, or MCP replay occurs. Gateway owns the top-level close taxonomy, and a close reason never proves whether a command committed. diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 1a5a18d5a6..87cb14f20e 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -27,7 +27,9 @@ class TransientUpstreamSmokeFailure(ProbeOperationalFailure): RETRYABLE_STARTUP_COMMAND_LABELS = frozenset({"WORLDS", "LOGIN"}) INVALID_COMMAND_LINE_ERROR = "commands must not contain embedded CR or LF" PLAINTEXT_TELNET_HOST_ERROR = "tls_enabled=False requires a localhost-equivalent Telnet host" -WORLD_DISCOVERY_ROW = re.compile(r"^\s*(\d+)\)\s+.+\s+\(([^()\r\n]+)\)\s*$") +WORLD_DISCOVERY_ROW = re.compile( + r"^\s*\S(?:.*?\S)?\s+\(([^()\r\n]+)\)\s*$" +) WORLD_DISCOVERY_POLL_INTERVAL_SECONDS = 0.5 RETRYABLE_UPSTREAM_FAILURE_PREFIXES = ("ERROR UPSTREAM_FAILURE", "ERROR UNAVAILABLE") DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES = ( @@ -206,20 +208,13 @@ def worlds_response_contains_selector(response, selector): if not isinstance(selector, str) or not selector.strip(): raise ValueError("World discovery selector must be a non-empty string") normalized_selector = selector.strip().casefold() - rows = [] + slugs = [] for line in response.splitlines(): match = WORLD_DISCOVERY_ROW.fullmatch(line) if match is not None: - rows.append((int(match.group(1)), match.group(2).strip().casefold())) + slugs.append(match.group(1).strip().casefold()) - try: - ordinal_selector = int(normalized_selector) - except ValueError: - ordinal_selector = None - if ordinal_selector is not None: - matches = [row for row in rows if row[0] == ordinal_selector] if ordinal_selector >= 1 else [] - else: - matches = [row for row in rows if row[1] == normalized_selector] + matches = [slug for slug in slugs if slug == normalized_selector] if len(matches) > 1: raise ProbeOperationalFailure(f"Configured smoke world selector {selector!r} appears ambiguously in WORLDS") diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 5520ad7bf1..f315ec186b 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1063,7 +1063,7 @@ assert opened[0].closed is True discovery_session = CommandResponseSession( [ "OK WORLDS\n", - "OK WORLDS\n1) Builder Sandbox (sandbox)\n2) Demo World (demo)\n", + "OK WORLDS\nBuilder Sandbox (sandbox)\nDemo World (demo)\n", "OK LOGIN\n", "OK PLAY Entered world: demo\n", "OK LOOK\n", @@ -1094,7 +1094,7 @@ assert discovery_session.sent == [ ] assert discovery_responses == [ "OK WORLDS\n", - "OK WORLDS\n1) Builder Sandbox (sandbox)\n2) Demo World (demo)\n", + "OK WORLDS\nBuilder Sandbox (sandbox)\nDemo World (demo)\n", "OK LOGIN\n", "OK PLAY Entered world: demo\n", "OK LOOK\n", @@ -1108,6 +1108,31 @@ assert [result["label"] for result in discovery_results] == [ ] +# Discovery matches exact displayed slugs; a numeric selector is a numeric +# slug, never the position of a row in the list. +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\nDemo World (demo)\nNumeric World (123)\n", "123" +) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\nDemo World (demo)\nFirst World (1)\n", "1" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\nDemo World (demo)\nNumeric World (123)\n", "2" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\nDemonstration World (demonstration)\n", "demo" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\nDemo World (demo-tools)\n", "demo" +) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\n1) Ranked World (ranked)\n", "ranked" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\nWelcome to the demo world\n", "demo" +) + + for transient_error in ( "ERROR UPSTREAM_FAILURE WORLDS is temporarily unavailable.\n", "ERROR UPSTREAM_UNAVAILABLE WORLDS is temporarily unavailable.\n", @@ -1118,7 +1143,7 @@ for transient_error in ( session = CommandResponseSession( [ transient_error, - "OK WORLDS\n1) Demo World (demo)\n", + "OK WORLDS\nDemo World (demo)\n", "OK LOGIN\n", "OK PLAY Entered world: demo\n", ] @@ -1217,7 +1242,7 @@ login_failure_attempts = [] def open_after_discovery_login_failure(): session = CommandResponseSession( [ - "OK WORLDS\n1) Demo World (demo)\n", + "OK WORLDS\nDemo World (demo)\n", "ERROR UPSTREAM_FAILURE Login is temporarily unavailable.\n", ] ) @@ -1251,7 +1276,7 @@ assert login_failure_attempts[0].sent == ["WORLDS\r\n", "LOGIN demo swordfish\r\ fragmented_discovery_session = CommandResponseSession( [ - ["OK WORLDS\n", "1) Demo World (demo)\n"], + ["OK WORLDS\n", "Demo World (demo)\n"], "OK LOGIN\n", "OK PLAY Entered world: demo\n", "OK LOOK\n", @@ -1280,7 +1305,7 @@ assert fragmented_discovery_session.sent == [ # complete logical messages and only splits the header from the complete row. fragmented_telnet_session = CommandResponseSession( [ - ["OK WORLDS\n1) Demo", " World (de", "mo)\n"], + ["OK WORLDS\nDemo", " World (de", "mo)\n"], "OK LOGIN\n", "OK PLAY Entered world: demo\n", ] @@ -1314,11 +1339,10 @@ class RepeatingWorldResponseSession(FakeSession): for selector, menu, expected_error in ( - ("Builder", "OK WORLDS\n1) Builder Sandbox (sandbox)\n", "was not listed"), - ("123", "OK WORLDS\n1) Numeric Slug (123)\n", "was not listed"), + ("Builder", "OK WORLDS\nBuilder Sandbox (sandbox)\n", "was not listed"), ( "demo", - "OK WORLDS\n1) Demo World (demo)\n2) Other Demo (demo)\n", + "OK WORLDS\nDemo World (demo)\nOther Demo (demo)\n", "appears ambiguously", ), ): diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 02bf464974..cb93e4dcb2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -6,6 +6,7 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.SQLException; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -13,6 +14,7 @@ import java.util.stream.Stream; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; +import net.firedevops.firemud.gamesession.service.AdmissionPointerConflictException; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import org.jooq.DSLContext; @@ -124,7 +126,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { } lockRuntimeTargetForCreation(entity); if (countByRuntimeTarget(entity.getTenantId(), entity.getGameInstanceId()) != 0) { - throw new IllegalStateException( + throw new AdmissionPointerConflictException( "Admission pointer creation conflicted with another route for the runtime target"); } entity.setRealmId(UUID.randomUUID()); @@ -137,6 +139,10 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { try { record.store(); } catch (IntegrityConstraintViolationException ex) { + if (isUniqueConstraintViolation(ex)) { + throw new AdmissionPointerConflictException( + "Admission pointer creation conflicted with another committed pointer", ex); + } throw new IllegalStateException( "Admission pointer creation conflicted with another committed pointer", ex); } @@ -206,7 +212,7 @@ public GameplayAdmissionPointer updateExisting( countByRuntimeTargetExcludingId( entity.getTenantId(), entity.getGameInstanceId(), entity.getId()); if (destinationCount != 0) { - throw new IllegalStateException( + throw new AdmissionPointerConflictException( "Admission pointer update conflicted with another route for the runtime target"); } int updated; @@ -244,6 +250,10 @@ public GameplayAdmissionPointer updateExisting( .and(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq(expectedCatalogRevision))) .execute(); } catch (IntegrityConstraintViolationException ex) { + if (isUniqueConstraintViolation(ex)) { + throw new AdmissionPointerConflictException( + "Admission pointer update conflicted with another committed pointer", ex); + } throw new IllegalStateException( "Admission pointer update conflicted with another committed pointer", ex); } @@ -270,6 +280,16 @@ private static boolean isPositive(Long value) { return value != null && value > 0L; } + private static boolean isUniqueConstraintViolation(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState())) { + return true; + } + } + return false; + } + public void deleteAllInBatch() { dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER).execute(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java new file mode 100644 index 0000000000..d2fc534416 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.gamesession.service; + +public class AdmissionPointerConflictException extends IllegalStateException { + public AdmissionPointerConflictException(String message) { + super(message); + } + + public AdmissionPointerConflictException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java index 4d1442216d..651ba6a033 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -3,15 +3,19 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.SQLException; import java.util.List; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.gamesession.service.AdmissionPointerConflictException; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.IntegrityConstraintViolationException; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -153,6 +157,104 @@ void duplicateRetainedRowsRefuseMigrationWithoutChangingDataOrHistory() { assertThat(indexExists(dsl)).isFalse(); } + @Test + void actualUniqueIndexViolationsAreTypedAndRollBackPointerAndAuditWrites() { + DriverManagerDataSource dataSource = isolatedDataSource(); + migrateToVersion(dataSource, "1053"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DatabaseGameplayAdmissionPointerAuthorityService service = authorityService(dsl); + service.upsertPointer( + pointerMutation( + "one-world", + "production", + SINGLE_PUBLIC_TENANT_ID, + 9510201L, + true, + 0L, + 0L, + "first-public")); + + List pointersBeforeCreateConflict = + retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); + List eventsBeforeCreateConflict = + retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> + authorityService(DSL.using(configuration)) + .upsertPointer( + pointerMutation( + "another-world", + "production", + SINGLE_PUBLIC_TENANT_ID, + 9510202L, + true, + 0L, + 0L, + "duplicate-public-create")))) + .isInstanceOf(AdmissionPointerConflictException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThat(sqlState(failure)).isEqualTo("23505"); + }); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")) + .isEqualTo(pointersBeforeCreateConflict); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) + .isEqualTo(eventsBeforeCreateConflict); + + service.upsertPointer( + pointerMutation( + "preview-world", + "preview", + SINGLE_PUBLIC_TENANT_ID, + 9510203L, + false, + 0L, + 0L, + "preview-create")); + List pointersBeforeUpdateConflict = + retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); + List eventsBeforeUpdateConflict = + retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> + authorityService(DSL.using(configuration)) + .upsertPointer( + pointerMutation( + "preview-world", + "preview", + SINGLE_PUBLIC_TENANT_ID, + 9510203L, + true, + 1L, + 1L, + "duplicate-public-update")))) + .isInstanceOf(AdmissionPointerConflictException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThat(sqlState(failure)).isEqualTo("23505"); + }); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")) + .isEqualTo(pointersBeforeUpdateConflict); + assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) + .isEqualTo(eventsBeforeUpdateConflict); + assertThat( + scalarLong( + dsl, + "SELECT COUNT(*) FROM gameplay_admission_pointer WHERE tenant_id = ? " + + "AND world_slug = 'preview-world' AND visible = true " + + "AND public_production_realm = false", + SINGLE_PUBLIC_TENANT_ID)) + .isEqualTo(1L); + } + private static void seedRetainedPointerHistory( DriverManagerDataSource dataSource, boolean includeDuplicatePublicRows) { migrateToVersion(dataSource, "5"); @@ -276,6 +378,50 @@ private static long visiblePublicCount(DSLContext dsl, long tenantId) { tenantId); } + private static DatabaseGameplayAdmissionPointerAuthorityService authorityService(DSLContext dsl) { + return new DatabaseGameplayAdmissionPointerAuthorityService( + new GameplayAdmissionPointerRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl)); + } + + private static GameplayAdmissionPointerMutation pointerMutation( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean publicProductionRealm, + Long expectedPointerVersion, + Long expectedCatalogRevision, + String requestId) { + return new GameplayAdmissionPointerMutation( + worldSlug, + "World " + worldSlug, + realmSlug, + "Realm " + realmSlug, + tenantId, + gameInstanceId, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + "integration-test", + "cardinality conflict proof", + requestId, + expectedPointerVersion, + expectedCatalogRevision, + null); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } + private static long scalarLong(DSLContext dsl, String query, Object... bindings) { return Objects.requireNonNull( Objects.requireNonNull(dsl.fetchOne(query, bindings), "Expected one scalar query row") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index a9aa71e28d..2a24a3838f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -1,17 +1,20 @@ package net.firedevops.firemud.gamesession.repository; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.SQLException; import java.time.Instant; import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.service.AdmissionPointerConflictException; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -86,6 +89,82 @@ void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception } } + @Test + void saveClassifiesOnlyUniqueConstraintViolationsAsPointerConflicts() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-save-conflict;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + AdmissionPointerConflictException duplicateSelector = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.save(pointer(7L, 45L, "SHARED", "production"))); + + assertEquals("23505", sqlState(duplicateSelector)); + assertNotNull(duplicateSelector.getCause()); + + GameplayAdmissionPointer invalid = pointer(8L, 55L, "SHARED", "production"); + invalid.setCatalogRevision(0L); + IllegalStateException checkViolation = + assertThrows(IllegalStateException.class, () -> repository.save(invalid)); + + assertFalse(checkViolation instanceof AdmissionPointerConflictException); + assertEquals( + "Admission pointer creation conflicted with another committed pointer", + checkViolation.getMessage()); + assertNotNull(checkViolation.getCause()); + } + } + + @Test + void updateClassifiesUniqueConstraintViolationsAsPointerConflicts() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-update-conflict;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + GameplayAdmissionPointer seasonal = repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + seasonal.setRealmSlug("production"); + seasonal.setCatalogRevision(2L); + + AdmissionPointerConflictException duplicateSelector = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.updateExisting(seasonal, 1L, 1L)); + + assertEquals("23505", sqlState(duplicateSelector)); + assertNotNull(duplicateSelector.getCause()); + assertEquals( + "seasonal", + repository + .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "seasonal") + .orElseThrow() + .getRealmSlug()); + } + } + + @Test + void duplicateRuntimeTargetDetectionUsesPointerConflictException() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-runtime-conflict;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.save(pointer(7L, 44L, "SHARED", "seasonal"))); + } + } + @Test void tenantScopedPointerListExcludesOtherTenants() throws Exception { try (Connection connection = @@ -387,4 +466,13 @@ prepared_version_upgrade_id VARCHAR(64), ) """); } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index c1a716266d..a22b4573f2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -18,6 +19,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.AdmissionPointerConflictException; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -173,6 +175,43 @@ void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { eventCaptor.getValue().getPlayableStateNamespaceId()); } + @Test + void upsertPointerPropagatesCreationConflictWithoutAppendingAudit() { + AdmissionPointerConflictException conflict = + new AdmissionPointerConflictException("duplicate public pointer"); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) + .thenReturn(Optional.empty()); + when(pointerRepository.save(any(GameplayAdmissionPointer.class))).thenThrow(conflict); + + AdmissionPointerConflictException thrown = + assertThrows( + AdmissionPointerConflictException.class, + () -> service.upsertPointer(pointerMutation(44L, true, 0L, 0L))); + + assertSame(conflict, thrown); + verifyNoInteractions(eventRepository); + } + + @Test + void upsertPointerPropagatesUpdateConflictWithoutAppendingAudit() { + AdmissionPointerConflictException conflict = + new AdmissionPointerConflictException("duplicate public pointer"); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) + .thenReturn(Optional.of(existingPointerForTenant(7L))); + when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) + .thenThrow(conflict); + + AdmissionPointerConflictException thrown = + assertThrows( + AdmissionPointerConflictException.class, + () -> service.upsertPointer(pointerMutation(45L, true, 1L, 1L))); + + assertSame(conflict, thrown); + verifyNoInteractions(eventRepository); + } + @Test void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { GameplayAdmissionPointer existing = existingPointer(); From 1b48681c0d4bb0d154615fbd3c0d9c7cb453a46e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:15:52 +1300 Subject: [PATCH 17/23] Point controller takeover proof to its owning tracker section --- .../adr-0132-namespace-scoped-single-character-controller.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md index 8111b94468..4fcea04a7e 100644 --- a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md +++ b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding and lacks the target namespace key and durable binding-generation contract end to end. Local receiving source suppresses takeover region-exit events; its proof and remaining transfer gaps belong to [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#admission-and-gameplay-binding). These are implementation gaps, not evidence for the old target. +Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding and lacks the target namespace key and durable binding-generation contract end to end. Local receiving source suppresses takeover region-exit events; its proof and remaining transfer gaps belong to [Player Access and Session](../../project-management/implementation-tracking/player-access-and-session.md#text-protocol-and-credential-policy). These are implementation gaps, not evidence for the old target. ## Decision Record From 7967bfa0bba8bdd9499c78c8b6b85a78d2d01eb4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:07:53 +1300 Subject: [PATCH 18/23] test(tcp): expect retained destination after reconnect --- ...ionAccountCrossServiceIntegrationTest.java | 1 + .../testsupport/GameplayTelnetScenarios.java | 22 +++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index b08321835e..922791eb6a 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -485,6 +485,7 @@ void telnetReconnectAfterRevocationFailsClosed() throws Exception { GameplayTelnetScenarios.reconnectAfterReady( this::openTelnetClient, READY_LOOK_TEXT, + LookTestFixtures.DESTINATION_ROOM_ID, firstClient -> { firstClient.sendLine("MOVE north"); assertThat(firstClient.readBlockContainingOrTimeout("OK LOOK")) diff --git a/services/tcp-proxy-service/src/testFixtures/java/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetScenarios.java b/services/tcp-proxy-service/src/testFixtures/java/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetScenarios.java index ae2d0d8686..edc0b906c0 100644 --- a/services/tcp-proxy-service/src/testFixtures/java/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetScenarios.java +++ b/services/tcp-proxy-service/src/testFixtures/java/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetScenarios.java @@ -278,14 +278,24 @@ public static ThreePlayerScenario openReadyTrio( } public static ReconnectScenario reconnectAfterReady( - DriverFactory factory, Admission admission, DriverExercise firstSessionExercise) + DriverFactory factory, + Admission admission, + String reconnectReadyText, + DriverExercise firstSessionExercise) throws Exception { GameplayTelnetDriver first = openReady(factory, admission); try { firstSessionExercise.accept(first); List firstResponses = List.copyOf(first.responses()); first.close(); - GameplayTelnetDriver reconnecting = openReady(factory, admission); + Admission reconnectAdmission = + new Admission( + admission.email(), + admission.password(), + admission.world(), + admission.characterName(), + reconnectReadyText); + GameplayTelnetDriver reconnecting = openReady(factory, reconnectAdmission); return new ReconnectScenario(firstResponses, reconnecting); } catch (Exception ex) { closeQuietly(first, ex); @@ -294,9 +304,13 @@ public static ReconnectScenario reconnectAfterReady( } public static ReconnectScenario reconnectAfterReady( - DriverFactory factory, String readyText, DriverExercise firstSessionExercise) + DriverFactory factory, + String readyText, + String reconnectReadyText, + DriverExercise firstSessionExercise) throws Exception { - return reconnectAfterReady(factory, demoAdmission(readyText), firstSessionExercise); + return reconnectAfterReady( + factory, demoAdmission(readyText), reconnectReadyText, firstSessionExercise); } public static TakeoverScenario takeoverAfterAdmitted( From b10683e3a887991a6444b56f7eb5ace23be454eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:41:48 +1300 Subject: [PATCH 19/23] docs(test): align reconnect prompt and presence proof scope --- ...r-experience-commands-and-communication.md | 2 +- .../text/SessionResumptionFlowTest.java | 19 +------------------ 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 4d02d7e2be..ac7fe6dd82 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -22,7 +22,7 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. Direct-text `CHARS` validates identity and target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event; `WORLDS` and public-only `REALMS` snapshots remain supported, while authenticated private-realm retention is unavailable. `HELP`/`PLAY` guidance no longer recommends `CHARS` or numbered roster browsing, and a known-character selector is selection input rather than admission evidence. | `drift-found` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. R1424 passes 184 selected Game Session unit cases and two actual WebSocket composition cases covering direct-handler, dispatch, HELP, PLAY, locale rendering and refusal after runtime-pointer movement; this is bounded containment proof, not a full service suite or namespace-qualified actor-discovery implementation. R1430 additionally passes 293 selected catalog/command/gRPC unit cases and 11 PostgreSQL migration cases for the bounded local receiver; the reconciled cohort passes 1,203 selected cases plus a separate 20-case bootstrap suite, and fresh 11-image held-admission smoke at `4576b4f62c` passes with authenticated and independently empty cleanup. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Realm catalog and admission pointers](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.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); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [HelpCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.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); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [HelpCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. Namespace-qualified direct-text `CHARS` remains unavailable; the supported Account bootstrap/HTTP roster and current positive/negative `PLAY` behavior are separate boundaries recorded below. | -| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | +| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler gates fresh prompt composition on both effective prompt settings; [Game Session reconnect behavior](../../architecture/system-architecture-reconnection.md) owns that contract. The parameterized [WebSocket handler proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java) covers either disabled setting across buffered and empty reconnect inputs; it does not qualify retained private-context replay or a production semantic WebSocket consumer. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | | EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; current reconnect suppresses private-context presentation and current first-party LOGIN/PLAY deny; durable episode/generation-qualified replay and logout invalidation remain unproved. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output. Current WebSocket reconnect suppresses retained private-context presentation and first-party `LOGIN`/`PLAY` deny before legacy effects; durable `LOGOUT` invalidation and episode/generation-qualified replay remain unproved. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. The earlier [Social UUID preparation](#communication-social-and-presence) temporarily rejected numeric parent callers and had incompatible peers; the bounded supported UUID flow is restored through #3360 and #2972 as recorded above, without closing these privacy, grant or admission gaps. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. During the [Social UUID preparation](#communication-social-and-presence), parent numeric callers and outbound peers are incompatible; this row does not claim restored end-to-end behavior. | diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index bbb729a907..e3f1e4d859 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -24,7 +24,6 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.gamelogic.v1.LookResult; import net.firedevops.firemud.gamesession.client.AccountClient; @@ -126,8 +125,6 @@ class SessionResumptionFlowTest { private final HelpCommandHandler helpHandler = new HelpCommandHandler(); private final CommunicationCommandHandler communicationHandler = Mockito.mock(CommunicationCommandHandler.class); - private final JwtUtil gameplayJwtUtil = - new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( @@ -638,21 +635,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI } @Test - void freshScopedAndGlobalRoleClaimsDoNotElevatePresenceAcrossReconnect() { - String jwt = - gameplayJwtUtil.generateToken( - ACCOUNT_ID, - Map.of( - "accountId", - ACCOUNT_ID, - "globalRoles", - List.of("platformAdmin", "support", "billingAdmin"), - "scopedRoles", - Map.of("22", List.of("god", "tenantAdmin", "moderator")))); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - AuthenticateResponse.newBuilder().setAuthToken(jwt).setAccountId(ACCOUNT_ID).build()); - + void reconnectRestoresPlayerPresenceInTheCommandFlowFixture() { assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); assertEquals( From 7349ad1b6d69ca501c99a2b8b1cf416745e18bc6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:20:43 +1300 Subject: [PATCH 20/23] fix(game-session): classify Spring-translated pointer conflicts --- .../automation-and-scheduler-runtime.md | 2 +- .../GameplayAdmissionPointerRepository.java | 5 +- .../AdmissionPointerConflictException.java | 2 + ...ameplayAdmissionPointerRepositoryTest.java | 69 +++++++++++++++++++ 4 files changed, 75 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 9ae59c4567..de9d637484 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, supported gameplay-scoped `WORLDS` and `REALMS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. Unavailable direct-text `CHARS` does not publish an accepted `onCommand` event. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement, deliberate logout, and transport loss; takeover/replacement does not publish an `onLeaveRegion` event under [Reconnection](../../architecture/system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary) and [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, supported gameplay-scoped `WORLDS` and `REALMS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. Unavailable direct-text `CHARS` does not publish an accepted `onCommand` event. `onSpawn` is emitted for fresh `PLAY`; movement emits `onEnterRegion` and `onLeaveRegion`; deliberate logout and transport loss emit only `onLeaveRegion`; takeover/replacement emits neither region event under [Reconnection](../../architecture/system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary) and [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md). Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index cb93e4dcb2..29bc485cac 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -21,6 +21,7 @@ import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.exception.IntegrityConstraintViolationException; +import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -138,7 +139,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { populate(record, entity); try { record.store(); - } catch (IntegrityConstraintViolationException ex) { + } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { if (isUniqueConstraintViolation(ex)) { throw new AdmissionPointerConflictException( "Admission pointer creation conflicted with another committed pointer", ex); @@ -249,7 +250,7 @@ public GameplayAdmissionPointer updateExisting( .and(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION.eq(expectedPointerVersion)) .and(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq(expectedCatalogRevision))) .execute(); - } catch (IntegrityConstraintViolationException ex) { + } catch (IntegrityConstraintViolationException | DataIntegrityViolationException ex) { if (isUniqueConstraintViolation(ex)) { throw new AdmissionPointerConflictException( "Admission pointer update conflicted with another committed pointer", ex); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java index d2fc534416..051a0dd52b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AdmissionPointerConflictException.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamesession.service; public class AdmissionPointerConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + public AdmissionPointerConflictException(String message) { super(message); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 2a24a3838f..b40717c618 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -21,6 +22,11 @@ import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.jooq.autoconfigure.JooqAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.datasource.DriverManagerDataSource; class GameplayAdmissionPointerRepositoryTest { @Test @@ -149,6 +155,69 @@ void updateClassifiesUniqueConstraintViolationsAsPointerConflicts() throws Excep } } + @Test + void springJooqTranslationClassifiesOnlyUniqueConstraintViolationsAsPointerConflicts() { + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + "jdbc:h2:mem:gameplay-pointer-spring-translation;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", + "sa", + ""); + + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) + .withBean(DriverManagerDataSource.class, () -> dataSource) + .run( + context -> { + DSLContext dsl = context.getBean(DSLContext.class); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = + new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + AdmissionPointerConflictException saveConflict = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.save(pointer(7L, 45L, "SHARED", "production"))); + DataIntegrityViolationException translatedSaveFailure = + assertInstanceOf(DataIntegrityViolationException.class, saveConflict.getCause()); + assertEquals("23505", sqlState(translatedSaveFailure)); + assertNotNull(translatedSaveFailure.getCause()); + + GameplayAdmissionPointer seasonal = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + seasonal.setRealmSlug("production"); + seasonal.setCatalogRevision(2L); + AdmissionPointerConflictException updateConflict = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.updateExisting(seasonal, 1L, 1L)); + DataIntegrityViolationException translatedUpdateFailure = + assertInstanceOf( + DataIntegrityViolationException.class, updateConflict.getCause()); + assertEquals("23505", sqlState(translatedUpdateFailure)); + assertNotNull(translatedUpdateFailure.getCause()); + assertEquals( + "seasonal", + repository + .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "seasonal") + .orElseThrow() + .getRealmSlug()); + + GameplayAdmissionPointer invalid = pointer(8L, 55L, "SHARED", "production"); + invalid.setCatalogRevision(0L); + IllegalStateException checkViolation = + assertThrows(IllegalStateException.class, () -> repository.save(invalid)); + assertFalse(checkViolation instanceof AdmissionPointerConflictException); + DataIntegrityViolationException translatedCheckFailure = + assertInstanceOf( + DataIntegrityViolationException.class, checkViolation.getCause()); + String checkViolationSqlState = sqlState(translatedCheckFailure); + assertNotNull(checkViolationSqlState); + assertNotEquals("23505", checkViolationSqlState); + assertNotNull(translatedCheckFailure.getCause()); + }); + } + @Test void duplicateRuntimeTargetDetectionUsesPointerConflictException() throws Exception { try (Connection connection = From 2fea26e71de9ea3e3d98d7ce4612c1ef8f18a4b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:30:17 +1300 Subject: [PATCH 21/23] test(security): retain negative control-role coverage --- .../architecture/system-architecture-protocol-bridging.md | 2 +- .../firemud/common/security/SessionClaimsTest.java | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index aa4076062e..1238e25880 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -42,7 +42,7 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Account connect-token issuance separately fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay or token work; [Account runtime status](./microservices/account-service/runtime-and-data.md) owns the current endpoint boundary. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The current implementation caveat remains: explicit join is unimplemented, current text `PLAY` consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceeds only when the two admission fields are true; an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Account connect-token issuance separately fails closed with `AUTH_UNAVAILABLE` before membership, entitlement, pointer, replay or token work; [Account runtime status](./microservices/account-service/runtime-and-data.md) owns the current endpoint boundary. For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. Current text `PLAY` does not consume the Account producer’s emitted lifecycle/generation fields; its boolean admission predicate does not prove the target lifecycle gate. Direct-text `CHARS` is unavailable, while the separate Account HTTP/bootstrap roster does not complete that command boundary. Current connect-token issuance is fail-closed rather than a completed shortcut/token path; successful target character, grant, pointer and issuance ordering remains incomplete. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 21451e2463..26a6a4eef4 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -125,4 +125,12 @@ void hasPrivilegedRoleRecognizesTenantScopedControlPlaneRoles() { assertTrue(claims.hasPrivilegedRole()); } + + @Test + void hasPrivilegedRoleRejectsNonControlPlaneRoles() { + SessionClaims claims = + new SessionClaims("11", List.of(), Map.of("7", List.of("player")), false, null, null); + + assertFalse(claims.hasPrivilegedRole()); + } } From 37b6e44c7660babc1d3d4dbcc1bc5d8384156d87 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:12:49 +1300 Subject: [PATCH 22/23] docs: align Telnet reconnect admission outcomes --- design/architecture/system-architecture-reconnection.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index a3f9572c43..152a8793c8 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when an otherwise eligible public-production request reports `membershipExists=false` and target-only public repair would be required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text clients stop with non-actionable `JOIN_REQUIRED` and no membership mutation when an otherwise eligible public-production request reports `membershipExists=false` or `gameplayAdmissionAllowed=false` and target-only public repair would be required. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. - Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. Current first-party browser/mobile bootstrap/connect-token surfaces are partial and the complete flow, including `Join & Play`, remains target-only. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation only when an otherwise eligible public-production request reports `membershipExists=false` and explicit `JOIN` is required. An existing response with `gameplayAdmissionAllowed=false` remains the established denial. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/target-only conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text stops with non-actionable `JOIN_REQUIRED` and no membership mutation only when an otherwise eligible public-production request reports `membershipExists=false` or `gameplayAdmissionAllowed=false` and explicit `JOIN` is required. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: From 2cfe8195e6c5dd49c6347ab988828f07bd5c121f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:16:59 +1300 Subject: [PATCH 23/23] test(gameplay): prove transport closure and held browsing boundaries --- ...m-architecture-redis-reset-and-recovery.md | 2 +- .../text/SessionResumptionFlowTest.java | 4 ++ .../text/TextCommandInterpreterTest.java | 3 +- .../GatewayGameplayBridgeIntegrationTest.java | 44 ++++++++++++++++++- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 13a48e6578..90423de55c 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -236,7 +236,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | -| `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. New context/movement writes omit the raw delegation JWT; legacy reads project without rehydrating it or authorizing retained-value cleanup, as recorded by [Game Session runtime](./microservices/game-session-service/runtime-and-data.md#implementation-status). Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. New context/movement writes omit the raw delegation JWT; legacy reads return a non-secret projection without rewriting retained values, extending their TTL, rehydrating the JWT, or authorizing retained-value cleanup, as recorded by [Game Session runtime](./microservices/game-session-service/runtime-and-data.md#implementation-status). Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | | `session:game:direct-text-worlds:v1:` | Coordination | **Reset-sensitive, not preservable UI state** | Loss, expiry or an applicable session reset invalidates the original public WORLDS menu and requires fresh `WORLDS`. A present undecodable value is refused until actual key expiry; no current supported administrative repair path is implemented, so a malformed key without a TTL can block fresh discovery indefinitely, as defined by the linked menu owner; the old snapshot is never reconstructed or its expiry extended. A tenant/region reset cannot infer key membership from this tenantless UUID key or from the numeric transport-session ID, and must not use a wildcard scan to delete, rebuild, or preserve affected menus. Cluster reset drops the family. | Game Session owns one full-key-hashed key per canonical original proxy UUID. This is observational public UI only, contains no Account identity, credentials, REALMS scope, or JOIN intent, and is outside authenticated gameplay `--preserve-sessions` recovery. See [Direct-text WORLDS UI menu](./system-architecture-redis.md#direct-text-worlds-ui-menu). | | `session:game:initial-context:v1:*` | Coordination | **Reset-sensitive, non-preservable pre-auth state** | A whole-family invalidation declares its global impact and closes the affected initial-LOGIN boundary. A tenant or region reset cannot infer membership of tenantless records or delete this family under a tenant filter. Current recovery authority must qualify the exact global family, fence and protected binding before a physical closure continuation; missing records, retained receipts and bare absence never establish that qualification. | No expiry or recreation of missing/replaced/closed original contexts. The production external qualification producer remains unavailable; controlled fixture leases do not prove reset/restore continuity. See the [initial-context owner](./system-architecture-redis.md#initial-login-context-aggregate). | | `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index e3f1e4d859..7abc0816a1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -524,6 +524,10 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { assertFalse(lookAfterCutover.commandResult().accepted()); assertEquals("PLAY_REQUIRED", lookAfterCutover.commandResult().errorCode()); + TextCommandInterpretationResult realmsAfterCutover = + interpreter.interpret("1", "REALMS demo", false); + assertTrue(realmsAfterCutover.commandResult().accepted()); + TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); assertFalse(charsAfterCutover.commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index d8a1b995da..fb5bb0e772 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -549,8 +549,7 @@ void charsFailClosedAfterLoginWithoutReturningRoster() { + "Use PLAY [realm] with a known character name.", renderedResponse("CHARS demo", interpretation)); verify(entityManagementClient, never()) - .listCharactersByAccount( - "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); } @Test diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java index 1515193573..e52082dce9 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java @@ -32,6 +32,7 @@ import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; +import org.springframework.web.reactive.socket.CloseStatus; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.WebSocketMessage; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; @@ -92,6 +93,37 @@ void gatewayRebindsUpstreamAfterAbruptDropWithoutDroppingClientSocket() throws E .isEqualTo(UPSTREAM.seenTransportSessionIds().get(1)); } + @Test + @SuppressWarnings("removal") + void clientEdgeClosureClosesTheActualUpstreamBeforeTeardown() throws Exception { + ensureStarted(); + + WebSocketHttpHeaders headers = new WebSocketHttpHeaders(); + headers.add("X-Proxy-Client-IP", "203.0.113.10"); + headers.add("X-Proxy-Game-Instance-Id", "42"); + headers.add("X-Proxy-Tenant-Id", "22"); + headers.add("X-Proxy-Connection-Id", "bridge-test-conn"); + + UpstreamRuntimeState state = TEST_UPSTREAM_STATE.get(); + try (WebSocketTestProbe probe = WebSocketTestProbe.connect(GATEWAY.websocketUrl(), headers)) { + probe.awaitStartsWith("UPSTREAM_READY", Duration.ofSeconds(5)); + assertThat(state.connectionCount()).isEqualTo(1); + + probe.close(); + + TestAsyncAssertions.assertEventually( + "actual upstream WebSocket close after client edge closure", + Duration.ofSeconds(5), + () -> !state.closedUpstreamSessions().isEmpty()); + assertThat(state.closedUpstreamSessions()).hasSize(1); + assertThat(state.closedUpstreamSessions().get(0)).isNotNull(); + + Thread.sleep(Duration.ofMillis(750).toMillis()); + assertThat(state.connectionCount()).isEqualTo(1); + assertThat(state.seenTransportSessionIds()).hasSize(1); + } + } + @Test @SuppressWarnings("removal") void gatewayRebindsAfterRealUpstreamRestartWithoutDroppingClientSocket() throws Exception { @@ -297,7 +329,8 @@ public Mono handle(org.springframework.web.reactive.socket.WebSocketSessio .receive() .map(WebSocketMessage::getPayloadAsText) .concatMap(command -> handleCommand(session, command)) - .then()); + .then()) + .then(session.closeStatus().doOnNext(state::recordClosedUpstreamSession).then()); } private Mono handleCommand( @@ -314,6 +347,7 @@ private Mono handleCommand( private static final class UpstreamRuntimeState { private final List seenTransportSessionIds = new CopyOnWriteArrayList<>(); + private final List closedUpstreamSessions = new CopyOnWriteArrayList<>(); private final AtomicBoolean firstConnectionDropped = new AtomicBoolean(false); private final AtomicInteger connectionCount = new AtomicInteger(); @@ -333,6 +367,14 @@ List seenTransportSessionIds() { return seenTransportSessionIds; } + List closedUpstreamSessions() { + return List.copyOf(closedUpstreamSessions); + } + + void recordClosedUpstreamSession(CloseStatus closeStatus) { + closedUpstreamSessions.add(closeStatus); + } + boolean markFirstConnectionDropped() { return firstConnectionDropped.compareAndSet(false, true); }