package games.dmg.fantasystick.session; import games.dmg.fantasystick.items.CharacterSheets; import games.dmg.fantasystick.items.EquipmentStorage; import games.dmg.fantasystick.items.SessionControls; import games.dmg.fantasystick.persistence.CharacterRecord; import games.dmg.fantasystick.persistence.CharacterStorage; import games.dmg.fantasystick.persistence.EquipmentSessionStore; import java.math.BigInteger; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** * Server-thread equipment custody, optional native vitals overlay and intercepted defeat. * Rewards and active food overrides remain separate. Presentation is independently cleaned. No inventory/file transaction, * automatic retry or snapshot rollback is promised. The scheduler must defer onto * the server thread; diagnostics must be thread-safe and must not use Player APIs. */ public final class EquipmentSessions implements AutoCloseable { public record Notice(UUID player, String code, String message) { } public record Failure(UUID player, UUID session, Throwable cause) { } public record Active(UUID player, UUID session, UUID character) { } public record ActiveCharacter(Active session, CharacterRecord record) { } public record SelectedControl(Active session, int slot, String ability) { } private final CharacterStorage characters; private final EquipmentSessionStore receipts; private Supplier switchDelay; private java.util.function.BooleanSupplier roleplayDisabled = () -> false; private final Clock clock; private final Consumer nextTick; private final Consumer notices; private final Consumer diagnostics; private games.dmg.fantasystick.presentation.SessionPresentation presentation = games.dmg.fantasystick.presentation.SessionPresentation.NONE; private final SessionClaims claims = new SessionClaims(); private final EquipmentStorage equipment = new EquipmentStorage(); private SessionControls controls = new SessionControls(); private final CharacterSheets sheets = new CharacterSheets(); private final Map pending = new HashMap<>(); private final Map owned = new HashMap<>(); private final Map active = new HashMap<>(); // Covers reentrant inventory setters and client sync, not just asynchronous work. private final Map transitioning = new HashMap<>(); private Consumer cursorCustody = ignored -> { }; private boolean cursorCustodyAttached; private boolean closed; private java.util.function.BooleanSupplier adventureMode = () -> false; private AdventureModeLease gameModes = new AdventureModeLease(); private SessionVitals vitals; private boolean closeSweepFinished; private int persistenceOperations; private final CompletableFuture drained = new CompletableFuture<>(); private static final class Attempt { final Player player; final UUID owner; UUID character; CharacterRecord record; SessionClaims.Claim claim; UUID session; ItemStack[] snapshot; ItemStack cursor; EquipmentSessionMarker.Token entryMarker; boolean markerValidated; boolean acknowledged; boolean saving; boolean effectsStarted; String previousGameMode; boolean modeStarted; games.dmg.fantasystick.persistence.OrdinaryVitals ordinaryVitals; boolean vitalsStarted; boolean healthSaveRequested; boolean healthAcknowledged = true; boolean nativeRestored; boolean gearRestoredForModeRecovery; boolean presentationInstalled; boolean cleaning; boolean cleanupAttempted; boolean uncertainSave; boolean nativeUncertain; boolean exitRequested; Duration exitDelay; boolean arrival; Attempt recoveryOwner; org.bukkit.Location entryLocation; boolean defeated; boolean deathResolved; boolean gearAcknowledged; boolean bookAttempted; boolean bookDelivered; boolean deliveryInvalidated; boolean conversionReported; ItemStack deathReference; org.bukkit.inventory.InventoryView deathView; Attempt(Player player, UUID owner, UUID character) { this.player = player; this.owner = owner; this.character = character; } } public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Consumer nextTick, Consumer notices, Consumer diagnostics) { this(characters, receipts, switchDelay, Clock.systemUTC(), nextTick, notices, diagnostics); } /** Supply the same wall clock as persistence when testing entry/exit deadline boundaries. */ public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock, Consumer nextTick, Consumer notices, Consumer diagnostics) { this.characters = Objects.requireNonNull(characters); this.receipts = Objects.requireNonNull(receipts); var initialSwitchDelay = Objects.requireNonNull(switchDelay); this.switchDelay = () -> initialSwitchDelay; this.clock = Objects.requireNonNull(clock); if (switchDelay.isNegative()) throw new IllegalArgumentException("Negative switch delay"); this.nextTick = Objects.requireNonNull(nextTick); this.notices = Objects.requireNonNull(notices); this.diagnostics = Objects.requireNonNull(diagnostics); } public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock, Consumer nextTick, Consumer notices, Consumer diagnostics, games.dmg.fantasystick.presentation.SessionPresentation presentation) { this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics); this.presentation = Objects.requireNonNull(presentation); } public EquipmentSessions(CharacterStorage characters, EquipmentSessionStore receipts, Duration switchDelay, Clock clock, Consumer nextTick, Consumer notices, Consumer diagnostics, games.dmg.fantasystick.presentation.SessionPresentation presentation, java.util.function.BooleanSupplier adventureMode, AdventureModeLease gameModes) { this(characters, receipts, switchDelay, clock, nextTick, notices, diagnostics, presentation); this.adventureMode = Objects.requireNonNull(adventureMode); this.gameModes = Objects.requireNonNull(gameModes); } /** Install before exposing entry so later checks/exits capture the acknowledged live policy. */ public synchronized void attachSwitchDelay(Supplier policy) { if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started"); switchDelay = Objects.requireNonNull(policy); if (switchDelay.get().isNegative()) throw new IllegalArgumentException("Negative switch delay"); } /** Install before exposing entry so pending and new activation work revalidates availability. */ public synchronized void attachRoleplayDisabled(java.util.function.BooleanSupplier policy) { if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started"); roleplayDisabled = Objects.requireNonNull(policy); } /** Install before exposing entry so registered definitions drive delivered control metadata. */ public synchronized void attachAbilityRegistry(games.dmg.fantasystick.ability.AbilityRegistry registry) { if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started"); controls = new SessionControls(Objects.requireNonNull(registry)); } /** Install before exposing entry; equipment-only adapter tests can omit the health overlay. */ public synchronized void attachVitals(SessionVitals value) { if (vitals != null || !owned.isEmpty()) throw new IllegalStateException("Vitals already attached or sessions started"); vitals = Objects.requireNonNull(value); } /** One server-thread custody bridge per coordinator; never called by persistence workers. */ synchronized void attachCursorCustody(Consumer invalidate) { if (cursorCustodyAttached) throw new IllegalStateException("Cursor custody already attached"); cursorCustody = Objects.requireNonNull(invalidate); cursorCustodyAttached = true; } private void invalidateCursor(UUID owner) { try { cursorCustody.accept(owner); } catch (RuntimeException failure) { diagnostic(new Failure(owner, null, failure)); } } /** * Completes after close's native sweep and all owned receipt/death mutations finish, * including failed or ambiguous outcomes. Retained receipts/conversions are not outstanding operations. * Observers cannot complete/cancel the lifetime authority. Does not await queued server tasks. */ public CompletionStage drained() { return drained.minimalCompletionStage(); } // All accounting, submissions and completion handlers share the lifecycle monitor. A handler // may submit its follow-up before its own reservation is released, including after close. private void persist(Supplier> operation, BiConsumer completion) { persistenceOperations++; CompletionStage work; try { work = operation.get(); } catch (RuntimeException failure) { work = CompletableFuture.failedStage(failure); } work.whenComplete((value, failure) -> { synchronized (EquipmentSessions.this) { try { completion.accept(value, failure); } finally { persistenceOperations--; finishDrain(); } } }); } private void finishDrain() { if (closeSweepFinished && persistenceOperations == 0 && transitioning.isEmpty()) drained.complete(null); } public synchronized Optional active(UUID player) { var attempt = active.get(player); return attempt == null ? Optional.empty() : Optional.of(new Active(player, attempt.session, attempt.character)); } /** Server-thread effect authorization: registry identity alone is not live custody. */ public synchronized boolean current(Active session) { var attempt = active.get(session.player()); return !closed && attempt != null && attempt.session.equals(session.session()) && attempt.character.equals(session.character()) && attempt.player.isOnline() && sheets.identify(attempt.player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent(); } /** Side-effect-free server-thread snapshots for exact active-character command resolution/autocomplete. */ public synchronized List activeCharacters() { if (closed) return List.of(); return active.values().stream().filter(attempt -> attempt.record != null) .map(attempt -> new ActiveCharacter(new Active(attempt.owner, attempt.session, attempt.character), attempt.record)) .filter(snapshot -> current(snapshot.session())).toList(); } /** Current active holder for a transferable identity, used only to synchronize acknowledged character writes. */ public synchronized Optional activeCharacter(UUID character) { Objects.requireNonNull(character); return active.values().stream().filter(attempt -> attempt.record != null && attempt.character.equals(character)) .filter(attempt -> current(new Active(attempt.owner, attempt.session, attempt.character))) .map(attempt -> new Active(attempt.owner, attempt.session, attempt.character)).findFirst(); } /** Current transferable character snapshot for a still-authorized server-thread action. */ public synchronized Optional currentRecord(Active session) { var attempt = active.get(session.player()); return current(session) && attempt != null && attempt.record != null ? Optional.of(attempt.record) : Optional.empty(); } /** Apply a persisted progression revision to the still-current active session. */ public synchronized boolean acknowledgeProgress(Active session, BigInteger expectedRevision, CharacterRecord saved) { var attempt = active.get(session.player()); if (closed || attempt == null || attempt.session == null || attempt.record == null || !attempt.session.equals(session.session()) || !attempt.character.equals(session.character()) || !attempt.record.revision().equals(expectedRevision) || !saved.id().equals(attempt.character) || !saved.revision().equals(expectedRevision.add(BigInteger.ONE)) || !current(session)) return false; var previous = attempt.record; if (vitals != null) vitals.updateProgress(attempt.player, attempt.session, previous, saved); attempt.record = saved; // Persisted truth precedes any reentrant native presentation setter. if (!previous.loadout().equals(saved.loadout())) { var refreshed = controls.create(saved, attempt.owner, attempt.session); for (int slot = 2; slot < 9; slot++) { if (active.get(attempt.owner) != attempt || !current(session)) return false; attempt.player.getInventory().setItem(slot, refreshed[slot]); } attempt.player.updateInventory(); // No planned native writes after this reentrant boundary. } return true; } /** Server-thread authorization for the currently held, issued control and saved loadout. */ public synchronized Optional selectedControl(Player player, ItemStack reported) { var attempt = active.get(player.getUniqueId()); if (closed || attempt == null || attempt.player != player || !player.isOnline() || attempt.record == null || !sheets.identify(player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent()) { return Optional.empty(); } int slot = player.getInventory().getHeldItemSlot(); var actual = player.getInventory().getItem(slot); var identity = controls.identify(actual).orElse(null); if (identity == null || identity.slot() != slot || !identity.owner().equals(attempt.owner) || !identity.session().equals(attempt.session) || !Objects.equals(actual, reported)) return Optional.empty(); String ability = ""; if (slot >= 2) { ability = controls.ability(actual).orElse(""); if (ability.isEmpty() || !ability.equals(attempt.record.loadout().get(slot - 2))) return Optional.empty(); } return Optional.of(new SelectedControl(new Active(attempt.owner, attempt.session, attempt.character), slot, ability)); } public synchronized void enter(Player player) { UUID owner = player.getUniqueId(); if (closed) return; if (roleplayDisabled.getAsBoolean()) { notice(owner, "ROLEPLAY_DISABLED", "Fantasy roleplaying is disabled; the character sheet was not activated."); return; } if (transitioning.containsKey(owner)) { notice(owner, "BUSY", "An equipment transition is still completing; retry afterwards."); return; } if (active.containsKey(owner)) return; cancelEntry(owner); if (owned.containsKey(owner)) { notice(owner, "BUSY", "Equipment persistence or recovery is pending; retry after it completes."); return; } var character = sheets.identify(player.getInventory().getItemInOffHand()); if (!player.isOnline() || character.isEmpty()) { notice(owner, "INVALID_SHEET", "Hold a valid live character sheet in your off hand."); return; } var attempt = new Attempt(player, owner, character.orElseThrow()); if (adventureMode.getAsBoolean() && player.getGameMode() != org.bukkit.GameMode.ADVENTURE) { attempt.previousGameMode = player.getGameMode().name(); } attempt.snapshot = snapshot(player); attempt.cursor = copy(player.getItemOnCursor()); pending.put(owner, attempt); characters.find(attempt.character).thenCombine(receipts.find(owner), Loaded::new) .whenComplete((loaded, failure) -> schedule(attempt, () -> loaded(attempt, loaded, failure))); } private record Loaded(Optional character, Optional state) { } private boolean entryNativeSafe(Attempt attempt, EquipmentSessionStore.State state) { if (hasRemnants(attempt.player) || !gameModes.available(attempt.player) || vitals != null && !vitals.available(attempt.player)) return false; var marker = EquipmentSessionMarker.read(attempt.player).orElse(null); if (EquipmentSessionMarker.present(attempt.player)) { // A terminal marker is resolved only by its matching completed file acknowledgment. // Keep it until the next successful entry; worker acknowledgments never touch PDC. var exit = state == null ? null : state.lastExit(); if (marker == null || marker.phase() != EquipmentSessionMarker.Phase.RESTORED || state == null || state.pending() != null || exit == null || !marker.matches(exit.sessionId(), exit.characterId())) return false; } attempt.entryMarker = marker; attempt.markerValidated = true; return true; } private static boolean hasRemnants(Player player) { return Arrays.stream(player.getInventory().getContents()).anyMatch(EquipmentSessions::remnant) || remnant(player.getItemOnCursor()); } private static boolean remnant(ItemStack item) { if (item == null || item.isEmpty() || !item.hasItemMeta()) return false; // Even malformed/foreign remnants are unsafe to pack as ordinary equipment. return item.getItemMeta().getPersistentDataContainer().getKeys().stream().anyMatch(key -> key.getNamespace().equals("fantasystick") && (key.getKey().startsWith("storage_") || key.getKey().startsWith("control_"))); } private synchronized void loaded(Attempt attempt, Loaded loaded, Throwable failure) { if (!entryCurrent(attempt) || attempt.claim != null) return; if (roleplayDisabled.getAsBoolean()) { refuse(attempt, "ROLEPLAY_DISABLED", "Fantasy roleplaying was disabled before activation completed."); return; } if (failure != null) { fail(attempt, failure); return; } var record = loaded.character().orElse(null); if (record == null || record.dead() || record.health().signum() <= 0) { refuse(attempt, "UNAVAILABLE_CHARACTER", "The saved character is missing, dead or has no health."); return; } if (loaded.state().isPresent()) { var state = loaded.state().orElseThrow(); if (state.pending() != null) { refuse(attempt, "RECOVERY_REQUIRED", "An unresolved equipment receipt requires validated recovery."); return; } Instant now = clock.instant(); if (!state.canEnter(attempt.character, switchDelay.get(), now)) { Duration remaining = Duration.between(now, state.lastExit().deadline()); long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1); refuse(attempt, "COOLDOWN", "Wait " + seconds + " seconds to switch characters (until " + state.lastExit().deadline() + "); the same character may be resumed now."); return; } } if (!entryNativeSafe(attempt, loaded.state().orElse(null))) { refuse(attempt, "NATIVE_RECOVERY_REQUIRED", "Native equipment marker or control/box remnants require inspection; entry did not change items."); return; } var refusal = equipment.refusal(attempt.player.getInventory(), attempt.owner, UUID.randomUUID()); if (refusal.isPresent()) { refuse(attempt, refusal.orElseThrow().name(), "Equipment entry refused: " + refusal.orElseThrow()); return; } // Restart receipts can belong to dead/missing characters, so they cannot acquire a // live SessionClaims token. Their unresolved equipment outcome still excludes entry. if (owned.values().stream().anyMatch(other -> attempt.character.equals(other.character))) { refuse(attempt, "CHARACTER_BUSY", "This character has an unresolved equipment session."); return; } attempt.claim = claims.tryClaim(attempt.owner, record).orElse(null); if (attempt.claim == null) { refuse(attempt, "CHARACTER_BUSY", "This character or player already has a session."); return; } attempt.session = attempt.claim.sessionId(); owned.put(attempt.owner, attempt); controls.create(record, attempt.owner, attempt.session); // Validate all nine controls before preparation/packing. if (vitals != null) attempt.ordinaryVitals = vitals.capture(attempt.player); attempt.saving = true; persist(() -> receipts.prepare(attempt.owner, attempt.session, attempt.character, attempt.previousGameMode, attempt.ordinaryVitals), (saved, error) -> { attempt.saving = false; if (error != null) { attempt.uncertainSave = true; fail(attempt, error); return; } attempt.acknowledged = true; if (!current(attempt)) { abandon(attempt); return; } // Queue the cross-worker read under lifecycle ownership: close cannot finish // its drain boundary and then have this callback submit fresh character IO. characters.find(attempt.character).whenComplete((fresh, readError) -> schedule(attempt, () -> complete(attempt, fresh, readError))); }); } private synchronized void complete(Attempt attempt, Optional fresh, Throwable failure) { if (!entryCurrent(attempt)) return; if (roleplayDisabled.getAsBoolean()) { refuse(attempt, "ROLEPLAY_DISABLED", "Fantasy roleplaying was disabled before activation completed."); return; } if (failure != null) { fail(attempt, failure); return; } var record = fresh.orElse(null); if (record == null || record.dead() || record.health().signum() <= 0) { refuse(attempt, "UNAVAILABLE_CHARACTER", "The saved character is no longer live."); return; } transitioning.put(attempt.owner, attempt); boolean packed = false; try { var items = controls.create(record, attempt.owner, attempt.session); attempt.entryLocation = attempt.player.getLocation().clone(); // Server thread, before activation. attempt.modeStarted = attempt.previousGameMode != null; if (!gameModes.enter(attempt.player, attempt.session, attempt.previousGameMode)) { attempt.modeStarted = false; // Returned refusal is not an uncertain setter exception. refuse(attempt, "GAME_MODE_REFUSED", "Adventure mode was refused; entry did not pack equipment."); return; } if (!entryCurrent(attempt) || attempt.exitRequested) return; attempt.effectsStarted = true; mark(attempt, EquipmentSessionMarker.Phase.PACKING); var result = equipment.pack(attempt.player.getInventory(), attempt.owner, attempt.session); if (result != EquipmentStorage.PackResult.PACKED) { EquipmentSessionMarker.clear(attempt.player); // Adapter refusal proves no inventory writes. attempt.effectsStarted = false; refuse(attempt, result.name(), "Equipment entry refused: " + result); return; } packed = true; try { sheets.applyModel(attempt.player.getInventory().getItemInOffHand()); } catch (RuntimeException cosmeticFailure) { diagnostic(attempt, cosmeticFailure); } if (interrupted(attempt)) return; for (int slot = 0; slot < 9; slot++) { attempt.player.getInventory().setItem(slot, items[slot]); if (interrupted(attempt)) return; } mark(attempt, EquipmentSessionMarker.Phase.PACKED); if (vitals != null) { attempt.vitalsStarted = true; attempt.healthAcknowledged = false; vitals.enter(attempt.player, attempt.session, attempt.ordinaryVitals, record); if (attempt.exitRequested || !current(attempt)) return; } pending.remove(attempt.owner, attempt); if (!attempt.exitRequested) { attempt.record = record; active.put(attempt.owner, attempt); attempt.presentationInstalled = true; try { presentation.activate(attempt.player, attempt.session, record); } catch (RuntimeException | LinkageError error) { withdrawPresentation(attempt); diagnostic(attempt, error); } } attempt.player.updateInventory(); } catch (RuntimeException error) { fail(attempt, error); // Effects may have started: never roll back or replay them. notice(attempt.owner, "NATIVE_UNCERTAIN", "Equipment mutation failed; items and receipt require inspection."); } finally { if (!active.containsKey(attempt.owner) && attempt.modeStarted) { restoreGameMode(attempt); if (!attempt.effectsStarted && attempt.exitRequested) pending.remove(attempt.owner, attempt); if (!attempt.effectsStarted && !current(attempt)) abandon(attempt); } transitioning.remove(attempt.owner, attempt); // The deferred exit must reserve persistence before drain can be signalled. try { if (packed && !attempt.nativeUncertain && !attempt.defeated && attempt.exitRequested) restoreExit(attempt); } finally { finishDrain(); } } } private boolean interrupted(Attempt attempt) { if (current(attempt) || attempt.exitRequested) return false; notice(attempt.owner, "ENTRY_INTERRUPTED", "Entry was cancelled during packing; the genuine box and receipt were retained for recovery."); return true; } /** * Ends mode without awaiting IO. Reentrant calls during an owned native transition request * teardown at that transition's boundary and return NOT_FOUND (no separate restore ran). * A native exception returns INVALID_BOX with NATIVE_UNCERTAIN notice/diagnostic; never retry it. */ public synchronized EquipmentStorage.RestoreResult exit(Player player) { UUID owner = player.getUniqueId(); var transition = transitioning.get(owner); if (transition != null) { captureExitDelay(transition); active.remove(owner, transition); withdrawPresentation(transition); transition.exitRequested = true; invalidateCursor(owner); return EquipmentStorage.RestoreResult.NOT_FOUND; } cancelEntry(owner); var attempt = active.remove(owner); if (attempt == null) { invalidateCursor(owner); return EquipmentStorage.RestoreResult.NOT_FOUND; } captureExitDelay(attempt); return restoreExit(attempt); } /** * Paper dispatches death before inventory clearing/drop spawning. Cancellation returns from * ServerPlayer.die; keepInventory is neither needed nor sufficient for this transition. * Only an active session owns defeat. Later ordinary deaths and prior vetoes stay ordinary. */ public synchronized void defeat(org.bukkit.event.entity.PlayerDeathEvent event) { if (closed || event.isCancelled()) return; UUID owner = event.getEntity().getUniqueId(); var attempt = active.remove(owner); if (attempt == null) { var transition = transitioning.get(owner); if (transition != null && transition.defeated) { // Contain only reentrance inside this native defeat, not a later ordinary // lethal outcome. This is not a grace period or post-defeat invulnerability. event.setCancelled(true); event.setReviveHealth(Objects.requireNonNull(event.getEntity() .getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue()); } return; } withdrawPresentation(attempt); attempt.defeated = true; event.setCancelled(true); boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null; // Submit first: any subsequent native getter/setter/notice can reenter disable, which // closes CharacterStorage. No dependent character work is submitted after this point. persist(() -> characters.recordDeath(attempt.character), (dead, failure) -> { if (failure != null) { diagnostic(attempt, failure); conversionUncertain(attempt, "Death save failed or is uncertain"); return; } if (dead.isEmpty()) { conversionUncertain(attempt, "Character was missing or already dead; no new Tail authorized"); return; } attempt.deathResolved = true; if (closed) { conversionUncertain(attempt, "Shutdown before Tail conversion"); return; } try { nextTick.accept(() -> { synchronized (EquipmentSessions.this) { deliverTail(attempt, dead.orElseThrow()); } }); } catch (RuntimeException error) { diagnostic(attempt, error); conversionUncertain(attempt, "Tail callback rejected"); } }); try { attempt.deathReference = copy(attempt.player.getInventory().getItemInOffHand()); attempt.deathView = attempt.player.getOpenInventory(); restoreExit(attempt); // Read the current maximum after owned overlay cleanup, including legitimate // ordinary modifiers. Never reconstruct attributes from an entry snapshot. double maximum = Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue(); event.setReviveHealth(maximum); attempt.player.setHealth(maximum); // Native cancellation only fills health when <= 0. notice(attempt.owner, "DEFEAT", "§cYour character was defeated."); try { if (!attempt.player.teleport(attempt.entryLocation.clone())) { notice(attempt.owner, "DEFEAT_RETURN_FAILED", "Return to the session entry location was refused; you remain here."); } } catch (RuntimeException failure) { diagnostic(attempt, failure); notice(attempt.owner, "DEFEAT_RETURN_FAILED", "Return to the session entry location failed; you remain here."); } } catch (RuntimeException failure) { diagnostic(attempt, failure); conversionUncertain(attempt, "Native defeat transition failed; inspect retained equipment and death state"); } finally { if (reserved) transitioning.remove(attempt.owner, attempt); finishDrain(); } } /** No automatic delivery after quit/respawn, including a reconnect of the same Player ID. */ public synchronized void invalidateContext(UUID owner) { invalidateCursor(owner); cancelEntry(owner); invalidateTail(owner); } /** Invalidates deferred conversion only; does not move a cursor, box, sheet or controls. */ public synchronized void invalidateTail(UUID owner) { var attempt = owned.get(owner); if (attempt != null && attempt.defeated) attempt.deliveryInvalidated = true; } private void deliverTail(Attempt attempt, CharacterRecord dead) { if (attempt.bookAttempted) return; attempt.bookAttempted = true; // Even an exception after a native write never permits replay. try { if (!tailContext(attempt) || !Objects.equals(attempt.deathReference, copy(attempt.player.getInventory().getItemInOffHand())) || !sheets.identify(attempt.deathReference).filter(attempt.character::equals).isPresent() || attempt.deathReference.getAmount() < 1 || attempt.deathReference.getAmount() > attempt.deathReference.getMaxStackSize()) { conversionUncertain(attempt, "Tail destination/context is stale or equipment restoration is unresolved"); return; } // An exact captured stack of copied references represents ONE character, not N // deaths. Replace that whole stack with ONE book; never scan/delete other copies, // move items, overwrite a changed stack, or grant into an available slot. var book = new games.dmg.fantasystick.items.TailBooks().create(dead); attempt.player.getInventory().setItemInOffHand(book); if (!tailContext(attempt) || !book.equals(attempt.player.getInventory().getItemInOffHand())) { conversionUncertain(attempt, "Context changed during Tail write; delivery may already have happened"); return; } attempt.bookDelivered = true; release(attempt); sync(attempt); } catch (RuntimeException failure) { diagnostic(attempt, failure); conversionUncertain(attempt, "Tail native write failed or is uncertain; never replay"); } } private boolean tailContext(Attempt attempt) { if (closed || attempt.deliveryInvalidated || owned.get(attempt.owner) != attempt || !attempt.player.isOnline() || attempt.player.getOpenInventory() != attempt.deathView) return false; var marker = EquipmentSessionMarker.read(attempt.player).orElse(null); return marker != null && marker.matches(attempt.session, attempt.character) && marker.phase() == EquipmentSessionMarker.Phase.RESTORED; } private void conversionUncertain(Attempt attempt, String reason) { if (attempt.conversionReported) return; attempt.conversionReported = true; attempt.deliveryInvalidated = true; diagnostic(attempt, new IllegalStateException(reason + "; character " + attempt.character + ". Retain current items and authoritative state; no automatic reissue or revival.")); } private void withdrawPresentation(Attempt attempt) { if (!attempt.presentationInstalled) return; attempt.presentationInstalled = false; try { presentation.withdraw(attempt.owner, attempt.session); } catch (RuntimeException | LinkageError failure) { diagnostic(attempt, failure); } } private boolean restoreGameMode(Attempt attempt) { if (attempt.previousGameMode == null) return true; try { if (gameModes.restore(attempt.player, attempt.session, attempt.previousGameMode)) { attempt.modeStarted = false; return true; } } catch (RuntimeException failure) { diagnostic(attempt, failure); } notice(attempt.owner, "GAME_MODE_RECOVERY", "Game-mode restoration was refused or ambiguous; retained receipt requires inspection."); return false; } private EquipmentStorage.RestoreResult restoreExit(Attempt attempt) { captureExitDelay(attempt); active.remove(attempt.owner, attempt); withdrawPresentation(attempt); boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null; try { invalidateCursor(attempt.owner); saveRemainingHealth(attempt); boolean modeRestored = restoreGameMode(attempt); EquipmentStorage.RestoreResult result; try { result = restoreMarked(attempt); } catch (RuntimeException failure) { attempt.nativeUncertain = true; restoreVitals(attempt); // Proven health ownership is independent of uncertain equipment writes. persistExit(attempt, false); diagnostic(attempt, failure); notice(attempt.owner, "NATIVE_UNCERTAIN", "Restoration failed; items and receipt require inspection."); return EquipmentStorage.RestoreResult.INVALID_BOX; } boolean vitalsRestored = restoreVitals(attempt); if (result == EquipmentStorage.RestoreResult.RESTORED && (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged)) { attempt.gearRestoredForModeRecovery = true; } persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED && modeRestored && vitalsRestored); if (result != EquipmentStorage.RestoreResult.RESTORED) { notice(attempt.owner, result.name(), "Equipment recovery refused: " + result); } else sync(attempt); return result; } finally { if (reserved) transitioning.remove(attempt.owner, attempt); finishDrain(); } } private void mark(Attempt attempt, EquipmentSessionMarker.Phase phase) { EquipmentSessionMarker.write(attempt.player, attempt.session, attempt.character, phase); } private EquipmentStorage.RestoreResult restoreMarked(Attempt attempt) { invalidateCursor(attempt.owner); var marker = EquipmentSessionMarker.read(attempt.player); // Only a successful restoration observed by this process for this exact Player // permits finishing a mode-only retry. Serialized RESTORED alone proves nothing. if (attempt.gearRestoredForModeRecovery && !hasRemnants(attempt.player) && marker.filter(token -> token.matches(attempt.session, attempt.character) && token.phase() == EquipmentSessionMarker.Phase.RESTORED).isPresent()) { return EquipmentStorage.RestoreResult.RESTORED; } if (marker.filter(token -> token.matches(attempt.session, attempt.character) && token.phase() == EquipmentSessionMarker.Phase.PACKED).isEmpty()) { notice(attempt.owner, "NATIVE_MARKER", "Missing, malformed, mismatched or ambiguous native equipment marker; " + "expected session " + attempt.session + ", character " + attempt.character + ", observed " + marker.map(Object::toString).orElse("missing/malformed") + ". Items and receipt retained. RESTORED receipts require manual reconciliation too."); return EquipmentStorage.RestoreResult.INVALID_BOX; } mark(attempt, EquipmentSessionMarker.Phase.RESTORING); var result = equipment.restore(attempt.player.getInventory(), attempt.owner, attempt.session, item -> controls.owned(item, attempt.owner, attempt.session), attempt.player.getItemOnCursor(), attempt.player::setItemOnCursor); // Returned refusals are read-only. Exceptions must retain the ambiguous RESTORING phase. mark(attempt, result == EquipmentStorage.RestoreResult.RESTORED ? EquipmentSessionMarker.Phase.RESTORED : EquipmentSessionMarker.Phase.PACKED); return result; } private void sync(Attempt attempt) { try { attempt.player.updateInventory(); } catch (RuntimeException failure) { diagnostic(attempt, failure); } } private void saveRemainingHealth(Attempt attempt) { if (!attempt.vitalsStarted || attempt.defeated || attempt.healthSaveRequested) return; attempt.healthSaveRequested = true; // Failed/uncertain writes are not authority for an automatic replay. try { var remaining = vitals.remaining(attempt.player, attempt.session, attempt.ordinaryVitals); var limit = NativeHealthLimit.read(); persist(() -> characters.saveHealth(attempt.character, remaining, limit), (saved, failure) -> { if (failure != null || saved.isEmpty()) { diagnostic(attempt, failure != null ? failure : new IllegalStateException("Character unavailable for health save")); return; } attempt.healthAcknowledged = true; if (attempt.nativeRestored) persistExit(attempt, true); }); } catch (RuntimeException failure) { diagnostic(attempt, failure); } } private boolean restoreVitals(Attempt attempt) { if (vitals == null || attempt.ordinaryVitals == null) return true; try { if (vitals.restore(attempt.player, attempt.session, attempt.ordinaryVitals)) return true; } catch (RuntimeException failure) { diagnostic(attempt, failure); } notice(attempt.owner, "VITALS_RECOVERY", "Health/nutrition restoration was refused or ambiguous; retained receipt requires inspection."); return false; } private void captureExitDelay(Attempt attempt) { if (attempt.exitDelay != null) return; var delay = Objects.requireNonNull(switchDelay.get()); if (delay.isNegative()) throw new IllegalStateException("Negative switch delay policy"); attempt.exitDelay = delay; } private void persistExit(Attempt attempt, boolean restored) { captureExitDelay(attempt); // Recovery attempts have no process-local exit request to capture earlier. attempt.nativeRestored = restored; boolean complete = restored && (attempt.healthAcknowledged || attempt.defeated); attempt.saving = true; persist(() -> complete ? receipts.completeExit(attempt.owner, attempt.session, attempt.exitDelay) : receipts.recordExit(attempt.owner, attempt.session, attempt.exitDelay), (state, failure) -> { attempt.saving = false; if (failure != null) diagnostic(attempt, failure); else if (complete) { attempt.gearAcknowledged = true; release(attempt); } }); } /** Cancel pending activation and route every active player through ordinary restoration. */ public synchronized void disableRoleplay() { for (var attempt : java.util.List.copyOf(pending.values())) { refuse(attempt, "ROLEPLAY_DISABLED", "Fantasy roleplaying was disabled before activation completed."); } for (var attempt : java.util.List.copyOf(active.values())) exit(attempt.player); } public synchronized void cancelEntry(UUID player) { var attempt = pending.remove(player); if (attempt != null) abandon(attempt); } private void abandon(Attempt attempt) { if (attempt.modeStarted || attempt.effectsStarted || attempt.cleanupAttempted || attempt.uncertainSave) return; if (attempt.acknowledged) { attempt.cleaning = true; attempt.cleanupAttempted = true; persist(() -> receipts.clearReceipt(attempt.owner, attempt.session), (state, failure) -> { attempt.cleaning = false; if (failure == null) release(attempt); else diagnostic(attempt, failure); }); } else if (!attempt.saving) release(attempt); } private void release(Attempt attempt) { if (attempt.defeated && (!attempt.deathResolved || !attempt.gearAcknowledged || !attempt.bookDelivered)) return; owned.remove(attempt.owner, attempt); if (attempt.claim != null) attempt.claim.close(); } private boolean current(Attempt attempt) { return !closed && pending.get(attempt.owner) == attempt; } private boolean entryCurrent(Attempt attempt) { if (!current(attempt)) { abandon(attempt); return false; } if (!attempt.player.isOnline() || attempt.previousGameMode != null && !attempt.modeStarted && !attempt.player.getGameMode().name().equals(attempt.previousGameMode) || attempt.ordinaryVitals != null && !attempt.vitalsStarted && !vitals.unchanged(attempt.player, attempt.ordinaryVitals) || attempt.markerValidated && (EquipmentSessionMarker.present(attempt.player) != (attempt.entryMarker != null) || !Objects.equals(attempt.entryMarker, EquipmentSessionMarker.read(attempt.player).orElse(null))) || !Arrays.equals(attempt.snapshot, snapshot(attempt.player)) || !Objects.equals(attempt.cursor, copy(attempt.player.getItemOnCursor())) || !sheets.identify(attempt.player.getInventory().getItemInOffHand()).filter(attempt.character::equals).isPresent()) { refuse(attempt, "STALE_ENTRY", "Entry changed before preparation completed; retry with your current equipment."); return false; } return true; } private void refuse(Attempt attempt, String code, String message) { pending.remove(attempt.owner, attempt); abandon(attempt); notice(attempt.owner, code, message); } private void fail(Attempt attempt, Throwable failure) { if (attempt.effectsStarted && owned.get(attempt.owner) == attempt) attempt.nativeUncertain = true; pending.remove(attempt.owner, attempt); active.remove(attempt.owner, attempt); withdrawPresentation(attempt); if (attempt.vitalsStarted) { // Only native callbacks can reach this phase. Preserve observed character damage // before independent vitals teardown; the uncertain equipment receipt stays owned. saveRemainingHealth(attempt); restoreVitals(attempt); } abandon(attempt); diagnostic(attempt, failure); } private void diagnostic(Attempt attempt, Throwable failure) { diagnostic(new Failure(attempt.owner, attempt.session, failure)); } private void diagnostic(Failure failure) { try { diagnostics.accept(failure); } catch (RuntimeException ignored) { /* Observers cannot abort owned cleanup or shutdown. */ } } private void notice(UUID owner, String code, String message) { try { notices.accept(new Notice(owner, code, message)); } catch (RuntimeException failure) { diagnostic(new Failure(owner, null, failure)); } } private synchronized void schedule(Attempt attempt, Runnable callback) { // close already invalidates pending work and owns its never-packed cleanup. Accepted // reads may still finish, but must not require another task on a disabled scheduler. if (closed) return; try { nextTick.accept(() -> { synchronized (EquipmentSessions.this) { try { callback.run(); } catch (RuntimeException failure) { fail(attempt, failure); } } }); } catch (RuntimeException failure) { fail(attempt, failure); } } private static ItemStack copy(ItemStack item) { return item == null ? null : item.clone(); } private static ItemStack[] snapshot(Player player) { return Arrays.stream(player.getInventory().getContents()).map(EquipmentSessions::copy).toArray(ItemStack[]::new); } /** Explicit proof-based reconciliation; never infer restoration from an absent box. */ public synchronized void recover(Player player) { recover(player, false); } /** Join reconciliation: recover a pending receipt, otherwise request normal entry. */ public synchronized void arrive(Player player) { recover(player, true); } private void recover(Player player, boolean arrival) { UUID owner = player.getUniqueId(); invalidateCursor(owner); if (closed || !player.isOnline()) return; var previous = owned.get(owner); if (previous != null && previous.defeated && (arrival || previous.gearAcknowledged || previous.bookDelivered || previous.player != player)) { notice(owner, "DEFEAT_PENDING", "Death or Tail conversion is pending/uncertain; retained state requires inspection, not automatic replay."); return; } if (previous != null && previous.nativeUncertain) { notice(owner, "NATIVE_UNCERTAIN", "A native equipment write had an uncertain outcome; automatic restoration is unsafe. Retain items for inspection."); return; } if (transitioning.containsKey(owner) || active.containsKey(owner) || previous != null && (previous.saving || previous.cleaning)) { notice(owner, "BUSY", "A session transition is still pending; recovery did not change items."); return; } cancelEntry(owner); var attempt = new Attempt(player, owner, null); attempt.recoveryOwner = previous; // A recovered receipt has no process-local never-packed proof. attempt.effectsStarted = true; attempt.arrival = arrival; pending.put(owner, attempt); receipts.find(owner).whenComplete((state, failure) -> schedule(attempt, () -> recovered(attempt, state, failure))); } private synchronized void recovered(Attempt attempt, Optional state, Throwable failure) { if (!current(attempt)) return; pending.remove(attempt.owner, attempt); if (!attempt.player.isOnline()) return; if (owned.get(attempt.owner) != attempt.recoveryOwner) { notice(attempt.owner, "STALE_RECOVERY", "Session ownership changed after the recovery read; no old receipt was replayed."); return; } if (failure != null) { diagnostic(attempt, failure); return; } var receipt = state.map(EquipmentSessionStore.State::pending).orElse(null); if (receipt == null) { if (attempt.arrival) { if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player); else if (EquipmentSessionMarker.present(attempt.player) || hasRemnants(attempt.player)) { notice(attempt.owner, "NATIVE_RECOVERY_REQUIRED", "Native equipment remnants have no pending receipt; items were retained for inspection."); } return; // Ordinary no-sheet/no-receipt arrivals are not rejected entry attempts. } notice(attempt.owner, "NO_RECEIPT", "No saved equipment receipt is available; items were left unchanged."); return; } attempt.character = receipt.characterId(); attempt.session = receipt.sessionId(); attempt.previousGameMode = receipt.previousGameMode(); attempt.ordinaryVitals = receipt.ordinaryVitals(); attempt.vitalsStarted = attempt.ordinaryVitals != null; attempt.healthAcknowledged = !attempt.vitalsStarted; attempt.modeStarted = attempt.previousGameMode != null; var previous = owned.get(attempt.owner); if (previous != null && !attempt.session.equals(previous.session)) { notice(attempt.owner, "SESSION_MISMATCH", "Saved and process-local sessions disagree; items were left unchanged."); return; } if (previous != null && (previous.defeated || previous.vitalsStarted)) { // Explicit same-lifetime equipment recovery still uses matching receipt/PACKED // proof. Keep the original death authority and its pending worker completion; // do not replace it with a recovery Attempt that could release its claim early. previous.deliveryInvalidated = true; restoreExit(previous); return; } if (previous != null) { attempt.claim = previous.claim; attempt.gearRestoredForModeRecovery = previous.player == attempt.player && previous.gearRestoredForModeRecovery; } owned.put(attempt.owner, attempt); transitioning.put(attempt.owner, attempt); try { saveRemainingHealth(attempt); boolean modeRestored = restoreGameMode(attempt); var result = restoreMarked(attempt); boolean vitalsRestored = restoreVitals(attempt); if (result == EquipmentStorage.RestoreResult.RESTORED) { if (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged) attempt.gearRestoredForModeRecovery = true; persistExit(attempt, modeRestored && vitalsRestored); sync(attempt); } else notice(attempt.owner, result.name(), "Equipment recovery refused: " + result + "; receipt and items retained."); } catch (RuntimeException error) { fail(attempt, error); notice(attempt.owner, "NATIVE_UNCERTAIN", "Recovery mutation failed; native phase, items and receipt retained for inspection."); } finally { transitioning.remove(attempt.owner, attempt); finishDrain(); } } @Override public synchronized void close() { if (closed) return; closed = true; try { for (var attempt : transitioning.values()) { attempt.exitRequested = true; withdrawPresentation(attempt); } // Accepted main-thread tasks may be discarded on disable. Report now as well as // from worker completion; neither path needs a scheduler on a disabled plugin. for (var attempt : java.util.List.copyOf(owned.values())) { if (attempt.defeated && !attempt.bookDelivered) conversionUncertain(attempt, "Shutdown before confirmed Tail conversion"); } for (var owner : java.util.List.copyOf(pending.keySet())) cancelEntry(owner); for (var attempt : java.util.List.copyOf(active.values())) exit(attempt.player); claims.close(); } finally { closeSweepFinished = true; finishDrain(); } } }