Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/session/EquipmentSessions.java
T
2026-10-06 18:33:38 -04:00

2087 lines
137 KiB
Java

package games.dmg.fantasystick.session;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.items.EquipmentStorage;
import games.dmg.fantasystick.items.GearItems;
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) { }
public record DefeatCapture(boolean playerDefeat,List<UUID> contributors,int victimLevel,BigInteger victimCoins){public DefeatCapture{contributors=List.copyOf(contributors);Objects.requireNonNull(victimCoins);}}
private final CharacterStorage characters;
private final EquipmentSessionStore receipts;
private Supplier<Duration> switchDelay;
private java.util.function.BooleanSupplier roleplayDisabled = () -> false;
private java.util.function.Function<UUID,DefeatCapture> defeatCapture=ignored->new DefeatCapture(false,List.of(),0,BigInteger.ZERO);
private java.util.function.Function<DownedEpisode,List<DownedEpisode.Reward>> downedRewardAllocation=ignored->List.of();
private games.dmg.fantasystick.events.DownedEventBridge downedEvents;
private games.dmg.fantasystick.events.SessionEventBridge sessionEvents;
private games.dmg.fantasystick.events.NutritionEventBridge nutritionEvents;
private NutritionPolicy nutritionPolicy;
private games.dmg.fantasystick.events.SwitchDelayEventBridge switchEvents;
private games.dmg.fantasystick.events.CharacterIdentityEventBridge identityEvents;
private games.dmg.fantasystick.events.EquipmentEventBridge equipmentEvents;
private games.dmg.fantasystick.events.SessionRecoveryEventBridge sessionRecoveryEvents;
private games.dmg.fantasystick.events.AdminActionEventBridge adminAudit;
private java.util.function.Function<DownedEpisode,CompletionStage<?>> downedDefeatRewards=ignored->CompletableFuture.completedStage(null);
private java.util.function.Predicate<UUID> unavailableCharacter = ignored -> false;
private java.util.function.Function<UUID,java.util.concurrent.CompletionStage<?>> partyDefeat =
ignored -> java.util.concurrent.CompletableFuture.completedStage(null);
private final Clock clock;
private final Consumer<Runnable> nextTick;
private final Consumer<Notice> notices;
private final Consumer<Failure> 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;
private GearItems gear;
private final CharacterSheets sheets = new CharacterSheets();
private final games.dmg.fantasystick.items.TailBooks tails = new games.dmg.fantasystick.items.TailBooks();
private final Map<UUID, Attempt> pending = new HashMap<>();
private final Map<UUID, Attempt> owned = new HashMap<>();
private final Map<UUID, Attempt> active = new HashMap<>();
private final Map<UUID, UUID> characterRecoveries = new HashMap<>();
private final java.util.Set<UUID> recoveryRecipients = new java.util.HashSet<>();
private final java.util.ArrayDeque<UUID> cooldownRefreshOrder = new java.util.ArrayDeque<>();
private final java.util.Set<UUID> cooldownRefreshQueued = new java.util.HashSet<>();
// Covers reentrant inventory setters and client sync, not just asynchronous work.
private final Map<UUID, Attempt> transitioning = new HashMap<>();
private Consumer<UUID> cursorCustody = ignored -> { };
private boolean cursorCustodyAttached;
private boolean closed;
private java.util.function.BooleanSupplier adventureMode = () -> false;
private AdventureModeLease gameModes = new AdventureModeLease();
private SessionVitals vitals;
private DownedDirectory downedDirectory;
private Supplier<Duration> downedTimeout=()->Duration.ofSeconds(300);
private Consumer<DownedEpisode> downedPresentation=ignored->{};
private boolean closeSweepFinished;
private int persistenceOperations;
private final CompletableFuture<Void> drained = new CompletableFuture<>();
private static final class Attempt {
final Player player;
final UUID owner;
UUID character;
CharacterSheets.Identity sheetIdentity;
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;
Instant nextCooldownVisualChange;
games.dmg.fantasystick.persistence.OrdinaryVitals ordinaryVitals;
boolean vitalsStarted;
boolean healthSaveRequested;
boolean healthSaveFailed;
boolean healthAcknowledged = true;
boolean nativeRestored;
boolean gearRestoredForModeRecovery;
boolean restorationRefused;
boolean receiptUncertain;
boolean presentationInstalled;
boolean cleaning;
boolean cleanupAttempted;
boolean uncertainSave;
boolean nativeUncertain;
boolean exitRequested;
games.dmg.fantasystick.events.SessionEventBridge.ExitCapture exitEvent;
boolean exitEventWritten;
games.dmg.fantasystick.events.NutritionEventBridge.Capture nutritionBeforeRestore;
games.dmg.fantasystick.events.NutritionEventBridge.Capture nutritionAfterRestore;
boolean nutritionRestoreWritten;
boolean nutritionRetainedWritten;
games.dmg.fantasystick.events.SwitchDelayEventBridge.ExitContext switchExit;
boolean switchEventWritten;
String exitReason = "voluntary";
java.math.BigInteger packReceiptRevision;
games.dmg.fantasystick.events.EquipmentEventBridge.Capture restoreEvent;
games.dmg.fantasystick.events.EquipmentEventBridge.Action restoreAction;
games.dmg.fantasystick.events.EquipmentEventBridge.Action recoveryAction;
games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action sessionRecoveryAction;
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminRecoveryAction;
games.dmg.fantasystick.events.EventInput.Location recoveryOriginalLocation;
games.dmg.fantasystick.events.EventInput.Location recoveryCurrentLocation;
String recoveryPriorPhase = "unavailable";
java.math.BigInteger recoveryReceiptRevision;
boolean recoveryResolved;
boolean sessionRecoveryResolved;
boolean restoreEventWritten;
Duration exitDelay;
boolean arrival;
boolean completedDeathRead;
Attempt recoveryOwner;
org.bukkit.Location entryLocation;
boolean defeated;
boolean downing;
boolean downedRelocation;
DownedEpisode downed;
DownedEpisode finalDowned;
DownedEpisode resumedDowned;
DownedEpisode resumedRevive;
boolean reviveHealthReconciled;
Instant downedProtectionUntil;
boolean downedPvpDefeat;
boolean deathResolved;
boolean gearAcknowledged;
boolean bookAttempted;
boolean bookDelivered;
boolean deliveryInvalidated;
boolean conversionReported;
boolean partyDefeatAcknowledged;
boolean tailCallbackQueued;
boolean defeatReturnTeleport;
CharacterRecord deathRecord;
ItemStack deathReference;
Object deathNativeReference;
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<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> 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<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> diagnostics) {
this.characters = Objects.requireNonNull(characters);
this.receipts = Objects.requireNonNull(receipts);
var initialSwitchDelay = Objects.requireNonNull(switchDelay);
this.switchDelay = () -> initialSwitchDelay;
this.clock = Objects.requireNonNull(clock);
this.controls = new SessionControls(new games.dmg.fantasystick.ability.AbilityRegistry(), 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<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> 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<Runnable> nextTick, Consumer<Notice> notices, Consumer<Failure> 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 attachGear(GearItems gear){if(closed||this.gear!=null)throw new IllegalStateException("Gear already attached or sessions closed");this.gear=Objects.requireNonNull(gear);}
public synchronized void attachSwitchDelay(Supplier<Duration> 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);
}
public synchronized void attachUnavailableCharacter(java.util.function.Predicate<UUID> predicate) {
if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started");
unavailableCharacter = Objects.requireNonNull(predicate);
}
public synchronized void attachPvpDefeat(java.util.function.Predicate<UUID> predicate){attachDefeatCapture(player->new DefeatCapture(predicate.test(player),List.of(),0,BigInteger.ZERO));}
public synchronized void attachDefeatCapture(java.util.function.Function<UUID,DefeatCapture> capture){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");defeatCapture=Objects.requireNonNull(capture);}
public synchronized void attachDownedRewardAllocation(java.util.function.Function<DownedEpisode,List<DownedEpisode.Reward>> allocation){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");downedRewardAllocation=Objects.requireNonNull(allocation);}
public synchronized void attachDownedEvents(games.dmg.fantasystick.events.DownedEventBridge events){if(!owned.isEmpty()||downedEvents!=null)throw new IllegalStateException("Downed events already attached or sessions started");downedEvents=Objects.requireNonNull(events);}
public synchronized void attachSessionEvents(games.dmg.fantasystick.events.SessionEventBridge events){if(!owned.isEmpty()||sessionEvents!=null)throw new IllegalStateException("Session events already attached or sessions started");sessionEvents=Objects.requireNonNull(events);}
public synchronized void attachNutritionEvents(games.dmg.fantasystick.events.NutritionEventBridge events){if(!owned.isEmpty()||nutritionEvents!=null)throw new IllegalStateException("Nutrition events already attached or sessions started");nutritionEvents=Objects.requireNonNull(events);}
public synchronized void attachNutritionPolicy(NutritionPolicy policy){if(!owned.isEmpty()||nutritionPolicy!=null)throw new IllegalStateException("Nutrition policy already attached or sessions started");nutritionPolicy=Objects.requireNonNull(policy);}
public synchronized void attachSwitchEvents(games.dmg.fantasystick.events.SwitchDelayEventBridge events){if(!owned.isEmpty()||switchEvents!=null)throw new IllegalStateException("Switch events already attached or sessions started");switchEvents=Objects.requireNonNull(events);}
public synchronized void attachIdentityEvents(games.dmg.fantasystick.events.CharacterIdentityEventBridge events){if(!owned.isEmpty()||identityEvents!=null)throw new IllegalStateException("Identity events already attached or sessions started");identityEvents=Objects.requireNonNull(events);}
public synchronized void attachEquipmentEvents(games.dmg.fantasystick.events.EquipmentEventBridge events){if(!owned.isEmpty()||equipmentEvents!=null)throw new IllegalStateException("Equipment events already attached or sessions started");equipmentEvents=Objects.requireNonNull(events);}
public synchronized void attachSessionRecoveryEvents(games.dmg.fantasystick.events.SessionRecoveryEventBridge events){if(!owned.isEmpty()||sessionRecoveryEvents!=null)throw new IllegalStateException("Recovery events already attached or sessions started");sessionRecoveryEvents=Objects.requireNonNull(events);}
public synchronized void attachAdminAudit(games.dmg.fantasystick.events.AdminActionEventBridge audit){if(closed||adminAudit!=null)throw new IllegalStateException("Admin audit already attached or sessions closed");adminAudit=Objects.requireNonNull(audit);}
public synchronized void attachDownedDefeatRewards(java.util.function.Function<DownedEpisode,CompletionStage<?>> settlement){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");downedDefeatRewards=Objects.requireNonNull(settlement);}
public synchronized List<DownedEpisode.Reward> finalRewards(DownedEpisode episode){return List.copyOf(downedRewardAllocation.apply(Objects.requireNonNull(episode)));}
public synchronized void attachPartyDefeat(java.util.function.Function<UUID,java.util.concurrent.CompletionStage<?>> mutation) {
if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started");
partyDefeat = Objects.requireNonNull(mutation);
}
/** 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), clock);
}
/** 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<UUID> 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<Void> 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 <T> void persist(Supplier<CompletionStage<T>> operation, BiConsumer<T, Throwable> completion) {
persistenceOperations++;
CompletionStage<T> 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 persistReturn(Runnable action){try{nextTick.accept(action);}catch(RuntimeException ignored){}}
private void finishDrain() {
if (closeSweepFinished && persistenceOperations == 0 && transitioning.isEmpty()) drained.complete(null);
}
public synchronized Optional<Active> active(UUID player) {
var attempt = active.get(player);
return attempt == null ? Optional.empty() : Optional.of(new Active(player, attempt.session, attempt.character));
}
/** Server-thread recovery gate; persistence still revalidates revision/generation/death atomically. */
public synchronized boolean availableForCharacterRecovery(UUID character, UUID recipient) {
Objects.requireNonNull(character); Objects.requireNonNull(recipient);
return availableForCharacterRecoveryNow(character, recipient)
&& !characterRecoveries.containsKey(character) && !recoveryRecipients.contains(recipient);
}
/** Process-lifetime custody closes the entry race while durable recovery is prepared and delivered. */
public synchronized Optional<CharacterRecoveryClaim> claimCharacterRecovery(UUID character, UUID recipient) {
Objects.requireNonNull(character); Objects.requireNonNull(recipient);
if (!availableForCharacterRecovery(character, recipient)) return Optional.empty();
characterRecoveries.put(character, recipient);
recoveryRecipients.add(recipient);
return Optional.of(new CharacterRecoveryClaim(character, recipient));
}
private boolean availableForCharacterRecoveryNow(UUID character, UUID recipient) {
if (closed || unavailableCharacter.test(character) || downedDirectory!=null&&downedDirectory.all().stream().anyMatch(value->value.character().equals(character)&&(value.phase()==DownedEpisode.Phase.PENDING||!value.published())) || active.containsKey(recipient)
|| pending.containsKey(recipient) || transitioning.containsKey(recipient)
|| owned.containsKey(recipient)) return false;
return java.util.stream.Stream.of(active.values(), pending.values(), transitioning.values(), owned.values())
.flatMap(java.util.Collection::stream)
.noneMatch(attempt -> character.equals(attempt.character));
}
public final class CharacterRecoveryClaim implements AutoCloseable {
private final UUID character;
private final UUID recipient;
private boolean released;
private CharacterRecoveryClaim(UUID character, UUID recipient) {
this.character = character;
this.recipient = recipient;
}
@Override public void close() {
synchronized (EquipmentSessions.this) {
if (released) return;
released = true;
characterRecoveries.remove(character, recipient);
recoveryRecipients.remove(recipient);
}
}
}
public synchronized void attachDowned(DownedDirectory directory,Supplier<Duration> timeout,Consumer<DownedEpisode> presentation){if(closed||downedDirectory!=null)throw new IllegalStateException("Downed state already attached or sessions closed");downedDirectory=Objects.requireNonNull(directory);downedTimeout=Objects.requireNonNull(timeout);downedPresentation=Objects.requireNonNull(presentation);}
public synchronized Optional<DownedEpisode> downed(UUID player){var attempt=active.get(player);if(attempt!=null&&attempt.downed!=null)return Optional.of(attempt.downed);var directory=downedDirectory;return directory==null?Optional.empty():directory.all().stream().filter(value->value.player().equals(player)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst();}
/** 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.downing && attempt.downed==null && attempt.session.equals(session.session())
&& attempt.character.equals(session.character()) && attempt.player.isOnline() && attempt.record != null
&& sheets.authorizes(attempt.player.getInventory().getItemInOffHand(), attempt.record);
}
/** Side-effect-free server-thread snapshots for exact active-character command resolution/autocomplete. */
public synchronized List<ActiveCharacter> 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<Active> 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();
}
/** Process-authority eligibility: safe on the serialized write worker; no native inventory/player calls. */
public synchronized boolean acceptsCoinAdjustment(UUID character) {
if (closed || characterRecoveries.containsKey(character) || unavailableCharacter.test(character)
|| downedDirectory != null && downedDirectory.all().stream().anyMatch(value -> value.character().equals(character)
&& (value.phase() == DownedEpisode.Phase.PENDING || !value.published()))) return false;
if (java.util.stream.Stream.of(pending.values(), transitioning.values()).flatMap(java.util.Collection::stream)
.anyMatch(attempt -> character.equals(attempt.character))) return false;
return owned.values().stream().filter(attempt -> character.equals(attempt.character))
.allMatch(attempt -> active.get(attempt.owner) == attempt && attempt.acknowledged && !attempt.downing
&& attempt.downed == null && !attempt.exitRequested && !attempt.defeated && !attempt.cleaning
&& !attempt.receiptUncertain && !attempt.uncertainSave && !attempt.nativeUncertain);
}
/** Current native holder for a still-authorized server-thread action. */
public synchronized Optional<Player> currentPlayer(Active session) {
var attempt = active.get(session.player());
return current(session) && attempt != null ? Optional.of(attempt.player) : Optional.empty();
}
/** Current transferable character snapshot for a still-authorized server-thread action. */
public synchronized Optional<CharacterRecord> currentRecord(Active session) {
var attempt = active.get(session.player());
return current(session) && attempt != null && attempt.record != null
? Optional.of(attempt.record) : Optional.empty();
}
/**
* Re-presents only the authentic slot-zero control for a current session. The transformer receives a fresh
* ordinary book control, so stale presentation metadata is never authoritative and construction failure leaves
* the current control untouched.
*/
public synchronized boolean presentBook(Active session, java.util.function.UnaryOperator<ItemStack> transformer) {
Objects.requireNonNull(transformer);
var attempt = active.get(session.player());
if (closed || attempt == null || attempt.record == null || !current(session)) return false;
var currentItem = attempt.player.getInventory().getItem(0);
var currentIdentity = controls.identify(currentItem).orElse(null);
if (currentIdentity == null || currentIdentity.slot() != 0 || !currentIdentity.owner().equals(attempt.owner)
|| !currentIdentity.session().equals(attempt.session)) return false;
ItemStack desired;
try {
desired = Objects.requireNonNull(transformer.apply(controls.create(attempt.record, attempt.owner, attempt.session)[0])).clone();
} catch (RuntimeException failure) {
diagnostic(new Failure(attempt.owner, attempt.character, failure));
return false;
}
var desiredIdentity = controls.identify(desired).orElse(null);
if (desiredIdentity == null || desiredIdentity.slot() != 0 || !desiredIdentity.owner().equals(attempt.owner)
|| !desiredIdentity.session().equals(attempt.session)) return false;
if (Objects.equals(currentItem, desired)) return true;
try {
attempt.player.getInventory().setItem(0, desired);
attempt.player.updateInventory();
return active.get(attempt.owner) == attempt && current(session);
} catch (RuntimeException failure) {
try { attempt.player.getInventory().setItem(0, currentItem); attempt.player.updateInventory(); }
catch (RuntimeException rollback) { failure.addSuppressed(rollback); }
diagnostic(new Failure(attempt.owner, attempt.character, failure));
return false;
}
}
public boolean restoreBook(Active session) { return presentBook(session, java.util.function.UnaryOperator.identity()); }
/** 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(gear!=null&&!previous.gear().equals(saved.gear()))gear.install(attempt.player.getInventory(),saved,attempt.owner,attempt.session);
if ((!previous.loadout().equals(saved.loadout()) || !previous.cooldowns().equals(saved.cooldowns())
|| !previous.passives().equals(saved.passives())) && !refreshControls(attempt, session)) return false;
return true;
}
/** Bounded server-tick refresh of active cooldown controls; persisted deadlines are not mutated. */
public synchronized void refreshCooldownControls(int maximumSessions) {
if (maximumSessions <= 0) throw new IllegalArgumentException("Cooldown refresh bound must be positive");
int checks = Math.min(maximumSessions, cooldownRefreshOrder.size());
for (int checked = 0; checked < checks; checked++) {
UUID owner = cooldownRefreshOrder.removeFirst();
var attempt = active.get(owner);
if (attempt == null || attempt.record == null || attempt.session == null) {
cooldownRefreshQueued.remove(owner);
continue;
}
cooldownRefreshOrder.addLast(owner);
if (attempt.nextCooldownVisualChange != null && !clock.instant().isBefore(attempt.nextCooldownVisualChange)) {
refreshControls(attempt, new Active(attempt.owner, attempt.session, attempt.character));
}
}
}
private void queueCooldownRefresh(Attempt attempt) {
if (cooldownRefreshQueued.add(attempt.owner)) cooldownRefreshOrder.addLast(attempt.owner);
}
private boolean refreshControls(Attempt attempt, Active session) {
var refreshed = controls.create(attempt.record, attempt.owner, attempt.session);
boolean changed = false;
for (int slot = 1; slot < 9; slot++) {
if (active.get(attempt.owner) != attempt || !current(session)) return false;
if (Objects.equals(attempt.player.getInventory().getItem(slot), refreshed[slot])) continue;
attempt.player.getInventory().setItem(slot, refreshed[slot]);
changed = true;
}
if (changed) attempt.player.updateInventory(); // No planned native writes after this reentrant boundary.
if (active.get(attempt.owner) != attempt || !current(session)) return false;
attempt.nextCooldownVisualChange = nextCooldownVisualChange(attempt.record);
return true;
}
private Instant nextCooldownVisualChange(CharacterRecord record) {
var now = clock.instant();
return record.loadout().stream().filter(ability -> !ability.isEmpty())
.map(record.cooldowns()::get).filter(Objects::nonNull).filter(deadline -> now.isBefore(deadline))
.min(Instant::compareTo).orElse(null);
}
/** Server-thread authorization for the currently held, issued control and saved loadout. */
public synchronized boolean currentControl(Player player, SelectedControl selected) {
if (selected == null) return false;
var attempt = active.get(player.getUniqueId());
if (closed || attempt == null || attempt.player != player || attempt.record == null
|| !current(selected.session()) || selected.slot() != player.getInventory().getHeldItemSlot()) return false;
var actual = player.getInventory().getItem(selected.slot());
var identity = controls.identify(actual).orElse(null);
if (identity == null || identity.slot() != selected.slot() || !identity.owner().equals(attempt.owner)
|| !identity.session().equals(attempt.session)) return false;
String ability = selected.slot() < 2 ? "" : controls.ability(actual).orElse("");
return ability.equals(selected.ability()) && (selected.slot() < 2
|| ability.equals(attempt.record.loadout().get(selected.slot() - 2)));
}
public synchronized Optional<SelectedControl> selectedControl(Player player, ItemStack reported) {
var attempt = active.get(player.getUniqueId());
if (closed || attempt == null || attempt.player != player || !player.isOnline() || attempt.record == null
|| !sheets.authorizes(player.getInventory().getItemInOffHand(), attempt.record)) {
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){enter(player,null);}
private void enter(Player player,DownedEpisode resumedDowned) {
UUID owner = player.getUniqueId();
if (closed) return;
if (recoveryRecipients.contains(owner)) {
notice(owner, "CHARACTER_RECOVERY", "Administrative character recovery is still completing.");
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);
var previous = owned.get(owner);
if (previous != null && previous.defeated) {
retryTail(player, previous);
return;
}
if (previous != null) {
notice(owner, "BUSY", "Equipment persistence or recovery is pending; retry after it completes.");
return;
}
var identity = sheets.identity(player.getInventory().getItemInOffHand());
if (!player.isOnline() || identity.isEmpty()) {
notice(owner, "INVALID_SHEET", "Hold a valid live character sheet in your off hand.");
return;
}
var character = identity.orElseThrow().character();
if(resumedDowned==null&&downedDirectory!=null)resumedDowned=downedDirectory.all().stream().filter(value->value.player().equals(owner)&&value.character().equals(character)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
if(resumedDowned!=null&&(!resumedDowned.player().equals(owner)||!resumedDowned.character().equals(character)||resumedDowned.phase()!=DownedEpisode.Phase.PENDING)){notice(owner,"DOWNED_RECOVERY_REQUIRED","Saved downed custody does not match the held sheet.");return;}
if (characterRecoveries.containsKey(character)) {
notice(owner, "CHARACTER_RECOVERY", "That character has unresolved administrative recovery custody.");
return;
}
if (resumedDowned==null&&unavailableCharacter.test(character)) {
notice(owner, "CHARACTER_IN_CUSTODY", "That character has unresolved external custody and cannot be activated.");
return;
}
var attempt = new Attempt(player, owner, character);
attempt.resumedDowned=resumedDowned;
if(resumedDowned==null&&downedDirectory!=null)attempt.resumedRevive=downedDirectory.all().stream().filter(value->value.player().equals(owner)&&value.character().equals(character)&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.REVIVED&&!value.published()).max(java.util.Comparator.comparing(DownedEpisode::resolvedAt)).orElse(null);
attempt.sheetIdentity = identity.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<CharacterRecord> character, Optional<EquipmentSessionStore.State> 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_") || key.getKey().startsWith("character_gear")));
}
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 (attempt.resumedDowned==null&&unavailableCharacter.test(attempt.character)) {
refuse(attempt, "CHARACTER_IN_CUSTODY", "That character entered unresolved external custody before activation completed."); return;
}
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(attempt.resumedRevive!=null&&!attempt.reviveHealthReconciled){attempt.reviveHealthReconciled=true;var maximum=record.maximumHealth().min(NativeHealthLimit.read());if(record.health().compareTo(maximum)<0){characters.saveHealth(record.id(),record.revision(),maximum,maximum).whenComplete((saved,saveFailure)->schedule(attempt,()->loaded(attempt,new Loaded(saved==null?Optional.empty():saved,loaded.state()),saveFailure)));return;}}
if(attempt.resumedDowned!=null&&(resolveWorld(attempt.player,attempt.resumedDowned.world())==null||resolveWorld(attempt.player,attempt.resumedDowned.entryWorld())==null)){refuse(attempt,"DOWNED_WORLD_UNAVAILABLE","Saved downed or return world is unavailable; custody remains unresolved.");return;}
if (!sheets.authorizes(attempt.player.getInventory().getItemInOffHand(), record)
|| attempt.sheetIdentity == null || !attempt.sheetIdentity.equals(
sheets.identity(attempt.player.getInventory().getItemInOffHand()).orElse(null))) {
refuse(attempt, "STALE_SHEET", "That character sheet generation is no longer authorized."); 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();
boolean admitted = state.canEnter(attempt.character, switchDelay.get(), now);
if (switchEvents != null) switchEvents.evaluated(attempt.player, attempt.character,
state, switchDelay.get(), now, admitted);
if (!admitted) {
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; the same character may be resumed now."); return;
}
} else if (switchEvents != null) switchEvents.evaluated(attempt.player, attempt.character,
null, switchDelay.get(), clock.instant(), true);
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()) {
if (equipmentEvents != null) {
var action = equipmentEvents.action(attempt.player, null, attempt.character, "equipment_pack_preflight");
equipmentEvents.resolved(action, "refused", refusal.orElseThrow().name().toLowerCase(java.util.Locale.ROOT));
}
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 = (attempt.resumedDowned==null?claims.tryClaim(attempt.owner,record):claims.tryClaim(attempt.owner,record,attempt.resumedDowned.session())).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(() -> attempt.resumedDowned==null?receipts.prepare(attempt.owner,attempt.session,attempt.character,attempt.previousGameMode,attempt.ordinaryVitals):receipts.resume(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;
attempt.packReceiptRevision = saved.revision();
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<CharacterRecord> 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.resumedDowned==null?attempt.player.getLocation().clone():location(resolveWorld(attempt.player,attempt.resumedDowned.entryWorld()),attempt.resumedDowned.entryX(),attempt.resumedDowned.entryY(),attempt.resumedDowned.entryZ(),attempt.resumedDowned.entryYaw(),attempt.resumedDowned.entryPitch()); // 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;
}
if(gear!=null)gear.install(attempt.player.getInventory(),record,attempt.owner,attempt.session);
mark(attempt, EquipmentSessionMarker.Phase.PACKED);
if (equipmentEvents != null) try {
equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).ifPresent(box -> equipmentEvents.packed(
equipmentEvents.capture(attempt.player, attempt.session, record, box), attempt.packReceiptRevision));
} catch (RuntimeException observationFailure) { diagnostic(attempt, observationFailure); }
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;
attempt.nextCooldownVisualChange = nextCooldownVisualChange(record);
active.put(attempt.owner, attempt);
queueCooldownRefresh(attempt);
attempt.presentationInstalled = true;
try { presentation.activate(attempt.player, attempt.session, record); }
catch (RuntimeException | LinkageError error) { withdrawPresentation(attempt); diagnostic(attempt, error); }
if(attempt.resumedDowned!=null){attempt.downed=attempt.resumedDowned;attempt.downing=false;attempt.downedRelocation=true;try{var episode=attempt.resumedDowned;var anchor=location(resolveWorld(attempt.player,episode.world()),episode.x(),episode.y(),episode.z(),episode.yaw(),episode.pitch());if(!attempt.player.teleport(anchor))throw new IllegalStateException("Saved downed anchor teleport was refused");attempt.player.setHealth(1);downedPresentation.accept(episode);}finally{attempt.downedRelocation=false;}}
else if(downedDirectory!=null)attempt.downedProtectionUntil=downedDirectory.all().stream().filter(value->value.player().equals(attempt.owner)&&value.character().equals(attempt.character)&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.REVIVED&&value.protectionUntil()!=null&&clock.instant().isBefore(value.protectionUntil())).max(java.util.Comparator.comparing(DownedEpisode::resolvedAt)).map(DownedEpisode::protectionUntil).orElse(null);
if(attempt.resumedRevive!=null){var recovered=attempt.resumedRevive;if(downedEvents!=null)downedEvents.outcomePublished(recovered);downedDirectory.publish(recovered.id(),recovered.outcomeOperation()).whenComplete((published,publishFailure)->{if(publishFailure!=null)diagnostic(attempt,publishFailure);else if(downedEvents!=null)downedEvents.outcomePublished(published);});}
}
attempt.player.updateInventory();
if(active.get(attempt.owner)==attempt&&sessionEvents!=null)sessionEvents.entered(attempt.player,attempt.session,record,attempt.entryLocation,attempt.resumedDowned!=null,attempt.previousGameMode!=null);
if(active.get(attempt.owner)==attempt&&nutritionEvents!=null)nutritionEvents.suspended(
attempt.player, attempt.session, record, attempt.ordinaryVitals, attempt.packReceiptRevision);
if(active.get(attempt.owner)==attempt&&identityEvents!=null)identityEvents.entered(attempt.player,attempt.session,record);
} 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) {
return exit(player, "voluntary");
}
public synchronized EquipmentStorage.RestoreResult exit(Player player, String reason) {
UUID owner = player.getUniqueId();
var transition = transitioning.get(owner);
if (transition != null) {
transition.exitReason = Objects.requireNonNull(reason);
captureExitDelay(transition);
active.remove(owner, transition);
withdrawPresentation(transition);
transition.exitRequested = true;
invalidateCursor(owner);
return EquipmentStorage.RestoreResult.NOT_FOUND;
}
cancelEntry(owner);
var current = active.get(owner);
if (current != null && nutritionPolicy != null) nutritionPolicy.flushNativeHealing(current.player);
var attempt = active.remove(owner);
if (attempt == null) { invalidateCursor(owner); return EquipmentStorage.RestoreResult.NOT_FOUND; }
attempt.exitReason = Objects.requireNonNull(reason);
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 downedStore=downedDirectory;var pendingAttempt=active.get(owner);
if(downedStore!=null&&pendingAttempt!=null){
if(pendingAttempt.downing||pendingAttempt.downed!=null){event.setCancelled(true);event.setReviveHealth(1);return;}
pendingAttempt.downing=true;var capturedDefeat=defeatCapture.apply(owner);pendingAttempt.downedPvpDefeat=capturedDefeat.playerDefeat();
var location=pendingAttempt.player.getLocation().clone();var causing=event.getDamageSource().getCausingEntity();var damageType=event.getDamageSource().getDamageType();var attribution=new DownedEpisode.Attribution(causing==null?null:causing.getUniqueId(),damageType==null?"unknown":damageType.getKey().asString(),capturedDefeat.playerDefeat(),capturedDefeat.contributors(),capturedDefeat.victimLevel(),capturedDefeat.victimCoins());
var work=downedStore.begin(pendingAttempt.character,pendingAttempt.owner,pendingAttempt.session,location.getWorld().getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch(),pendingAttempt.entryLocation.getWorld().getUID(),pendingAttempt.entryLocation.getX(),pendingAttempt.entryLocation.getY(),pendingAttempt.entryLocation.getZ(),pendingAttempt.entryLocation.getYaw(),pendingAttempt.entryLocation.getPitch(),pendingAttempt.record.name(),pendingAttempt.player.getName(),pendingAttempt.record.revision(),downedTimeout.get(),attribution);
event.setCancelled(true);event.setReviveHealth(1);
work.whenComplete((episode,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null){diagnostic(pendingAttempt,failure);notice(owner,"DOWNED_UNCERTAIN","Downed state could not be acknowledged; custody remains blocked.");return;}if(active.get(owner)!=pendingAttempt||!pendingAttempt.session.equals(episode.session()))return;pendingAttempt.downing=false;pendingAttempt.downed=episode;if(downedEvents!=null)downedEvents.downed(episode);notice(owner,"DOWNED","§cYou are downed. Accept death or wait for Revive.");try{downedPresentation.accept(episode);}catch(RuntimeException presentationFailure){diagnostic(pendingAttempt,presentationFailure);}}}));return;
}
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;
attempt.exitReason = "defeat";
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.
boolean loseCoins=defeatCapture.apply(owner).playerDefeat();
persist(() -> characters.recordDeath(attempt.character, loseCoins), (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;
attempt.deathRecord = dead.orElseThrow();
if (closed) { conversionUncertain(attempt, "Shutdown before party defeat and Tail conversion"); return; }
java.util.concurrent.CompletionStage<?> partyMutation;
try { partyMutation = partyDefeat.apply(attempt.character); }
catch (RuntimeException error) { diagnostic(attempt,error); conversionUncertain(attempt,"Party defeat mutation rejected"); return; }
partyMutation.whenComplete((ignored,partyFailure) -> {
synchronized (EquipmentSessions.this) {
if (partyFailure != null) { diagnostic(attempt,partyFailure); conversionUncertain(attempt,"Party defeat mutation failed"); return; }
if (closed) { conversionUncertain(attempt,"Shutdown before Tail conversion"); return; }
attempt.partyDefeatAcknowledged = true;
queueTail(attempt);
}
});
});
try {
var restored = restoreExit(attempt);
if (restored == EquipmentStorage.RestoreResult.RESTORED) {
var retained = attempt.player.getInventory().getItemInOffHand();
attempt.deathReference = copy(retained);
attempt.deathNativeReference = nativeIdentity(retained);
attempt.deathView = attempt.player.getOpenInventory();
}
// 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.");
attempt.defeatReturnTeleport = true;
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.");
} finally {
attempt.defeatReturnTeleport = false;
if (!attempt.deliveryInvalidated && owned.get(attempt.owner) == attempt && attempt.player.isOnline())
attempt.deathView = attempt.player.getOpenInventory();
}
} 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();
}
}
private static org.bukkit.World resolveWorld(Player player,UUID id){var current=player.getWorld();if(current!=null&&id.equals(current.getUID()))return current;return org.bukkit.Bukkit.getWorld(id);}
private static org.bukkit.Location location(org.bukkit.World world,double x,double y,double z,float yaw,float pitch){return new org.bukkit.Location(world,x,y,z,yaw,pitch);}
public synchronized boolean downedRelocation(UUID player){var attempt=active.get(player);return attempt!=null&&attempt.downedRelocation;}
public synchronized boolean downedProtected(UUID player){var attempt=active.get(player);return attempt!=null&&attempt.downed==null&&attempt.downedProtectionUntil!=null&&clock.instant().isBefore(attempt.downedProtectionUntil);}
/** Finish one durable Revive outcome on the exact retained active session. */
public synchronized void reviveDowned(DownedEpisode episode,Consumer<Boolean> completion){Objects.requireNonNull(episode);Objects.requireNonNull(completion);if(episode.phase()!=DownedEpisode.Phase.RESOLVED||episode.outcome()!=DownedEpisode.Outcome.REVIVED){completion.accept(false);return;}var attempt=active.get(episode.player());if(attempt==null||attempt.downed==null||!attempt.downed.id().equals(episode.id())||!attempt.session.equals(episode.session())||!attempt.character.equals(episode.character())){completion.accept(false);return;}var expected=attempt.record.revision();var maximum=attempt.record.maximumHealth().min(NativeHealthLimit.read());characters.saveHealth(attempt.character,expected,maximum,maximum).whenComplete((saved,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null||saved==null||saved.isEmpty()||active.get(attempt.owner)!=attempt||attempt.downed==null||!attempt.downed.id().equals(episode.id())){if(failure!=null)diagnostic(attempt,failure);completion.accept(false);return;}var record=saved.orElseThrow();try{if(vitals!=null&&!record.revision().equals(attempt.record.revision()))vitals.updateProgress(attempt.player,attempt.session,attempt.record,record);attempt.record=record;attempt.downed=null;attempt.downing=false;attempt.downedProtectionUntil=episode.protectionUntil();double nativeMaximum=Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue();attempt.player.setHealth(Math.min(nativeMaximum,record.health().doubleValue()));refreshControls(attempt,new Active(attempt.owner,attempt.session,attempt.character));attempt.player.closeInventory();notice(attempt.owner,"REVIVED","§aRevive restored your downed character.");completion.accept(true);}catch(RuntimeException publicationFailure){diagnostic(attempt,publicationFailure);completion.accept(false);}}}));}
/** Publish one already-durable final-death outcome through the existing restoration/Tail custody path. */
public synchronized boolean finalizeDowned(DownedEpisode episode){Objects.requireNonNull(episode);if(episode.phase()!=DownedEpisode.Phase.RESOLVED||episode.outcome()!=DownedEpisode.Outcome.FINAL_DEATH)return false;var attempt=active.get(episode.player());if(attempt==null){persist(()->recordOfflineFinalDeath(episode),(dead,failure)->{if(failure!=null)diagnostic(new Failure(episode.player(),episode.session(),failure));else if(dead.isEmpty())diagnostic(new Failure(episode.player(),episode.session(),new IllegalStateException("Offline final death conflicted with saved character")));});return true;}if(attempt.downed==null||!attempt.downed.id().equals(episode.id())||!attempt.session.equals(episode.session())||!attempt.character.equals(episode.character()))return false;active.remove(attempt.owner,attempt);attempt.finalDowned=episode;attempt.downed=null;withdrawPresentation(attempt);attempt.defeated=true;attempt.exitReason="defeat";boolean reserved=transitioning.putIfAbsent(attempt.owner,attempt)==null;boolean loseCoins=episode.attribution().playerDefeat();persist(()->characters.recordFinalDeath(attempt.character,attempt.record.revision(),episode.id(),episode.resolvedAt(),loseCoins),(dead,failure)->{if(failure!=null){diagnostic(attempt,failure);conversionUncertain(attempt,"Final death save failed or is uncertain");return;}if(dead.isEmpty()){conversionUncertain(attempt,"Character was missing or final death conflicted; no Tail authorized");return;}attempt.deathResolved=true;attempt.deathRecord=dead.orElseThrow();if(downedEvents!=null)downedEvents.finalDeathRecorded(episode);if(closed){conversionUncertain(attempt,"Shutdown before reward, party defeat and Tail conversion");return;}java.util.concurrent.CompletionStage<?> partyMutation=finalConsequences(episode);partyMutation.whenComplete((ignored,partyFailure)->{synchronized(EquipmentSessions.this){if(partyFailure!=null){diagnostic(attempt,partyFailure);conversionUncertain(attempt,"Party defeat mutation failed");return;}attempt.partyDefeatAcknowledged=true;queueTail(attempt);}});});try{var restored=restoreExit(attempt);if(restored==EquipmentStorage.RestoreResult.RESTORED){var retained=attempt.player.getInventory().getItemInOffHand();attempt.deathReference=copy(retained);attempt.deathNativeReference=nativeIdentity(retained);attempt.deathView=attempt.player.getOpenInventory();}double maximum=Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue();attempt.player.setHealth(maximum);notice(attempt.owner,"DEFEAT","§cYour character was defeated.");attempt.defeatReturnTeleport=true;try{boolean returned;try{returned=attempt.player.teleport(attempt.entryLocation.clone());}catch(RuntimeException uncertain){if(downedEvents!=null)downedEvents.returnAttempted(episode,"uncertain");throw uncertain;}if(downedEvents!=null)downedEvents.returnAttempted(episode,returned?"returned":"refused");if(!returned)notice(attempt.owner,"DEFEAT_RETURN_FAILED","Return to the session entry location was refused; you remain here.");}finally{attempt.defeatReturnTeleport=false;if(!attempt.deliveryInvalidated&&owned.get(attempt.owner)==attempt&&attempt.player.isOnline())attempt.deathView=attempt.player.getOpenInventory();}}catch(RuntimeException failure){diagnostic(attempt,failure);conversionUncertain(attempt,"Native final-death transition failed; inspect retained equipment and death state");}finally{if(reserved)transitioning.remove(attempt.owner,attempt);finishDrain();}return true;}
private CompletionStage<Void> finalConsequences(DownedEpisode episode){var result=new CompletableFuture<Void>();try{nextTick.accept(()->{CompletionStage<?> work;try{work=downedDefeatRewards.apply(episode).thenCompose(ignored->partyDefeat.apply(episode.character()));}catch(RuntimeException failure){result.completeExceptionally(failure);return;}work.whenComplete((ignored,failure)->{if(failure==null)result.complete(null);else result.completeExceptionally(failure);});});}catch(RuntimeException rejected){result.completeExceptionally(rejected);}return result;}
private CompletionStage<Optional<CharacterRecord>> recordOfflineFinalDeath(DownedEpisode episode){return characters.find(episode.character()).thenCompose(found->{if(found.isEmpty())return CompletableFuture.completedStage(Optional.empty());var current=found.orElseThrow();return characters.recordFinalDeath(episode.character(),current.revision(),episode.id(),episode.resolvedAt(),episode.attribution().playerDefeat());}).thenCompose(dead->{if(dead.isEmpty())return CompletableFuture.completedStage(dead);if(downedEvents!=null)downedEvents.finalDeathRecorded(episode);return finalConsequences(episode).thenApply(ignored->dead);});}
/** Replay only the saved entry return after native custody proof; ordinary native refusal retains the existing Tail fallback. */
private boolean returnRecoveredDeath(Attempt attempt, DownedEpisode episode) {
var world = resolveWorld(attempt.player, episode.entryWorld());
if (world == null) {
retainRecovery(attempt, "return_world_unavailable");
return false;
}
attempt.entryLocation = location(world, episode.entryX(), episode.entryY(), episode.entryZ(),
episode.entryYaw(), episode.entryPitch());
attempt.defeatReturnTeleport = true;
try {
boolean returned = attempt.player.teleport(attempt.entryLocation.clone());
if (downedEvents != null) downedEvents.returnAttempted(episode, returned ? "returned" : "refused");
if (!returned) notice(attempt.owner, "DEFEAT_RETURN_FAILED",
"Return to the session entry location was refused; you remain here.");
return true;
} catch (RuntimeException failure) {
attempt.nativeUncertain = true;
if (downedEvents != null) downedEvents.returnAttempted(episode, "uncertain");
conversionUncertain(attempt, "Recovered final-death return was uncertain; retained native custody");
diagnostic(attempt, failure);
return false;
} finally {
attempt.defeatReturnTeleport = false;
if (!attempt.deliveryInvalidated && owned.get(attempt.owner) == attempt && attempt.player.isOnline())
attempt.deathView = attempt.player.getOpenInventory();
captureRecoveryLocations(attempt);
}
}
/** Historical offline finalization has no pending receipt: the completed exit and native state must agree. */
private void reconcileCompletedDeath(Attempt attempt, EquipmentSessionStore.State state, DownedEpisode episode) {
var prior = attempt.recoveryOwner;
var exit = state == null ? null : state.lastExit();
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (state == null || state.pending() != null || exit == null
|| !exit.sessionId().equals(episode.session()) || !exit.characterId().equals(episode.character())
|| marker == null || !marker.matches(episode.session(), episode.character())
|| marker.phase() != EquipmentSessionMarker.Phase.RESTORED
|| resolveWorld(attempt.player, episode.entryWorld()) == null
|| hasRemnants(attempt.player) || prior != null && (prior.nativeUncertain
|| !prior.defeated || prior.receiptUncertain || !prior.gearAcknowledged
|| !deathProof(prior, episode))) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"Completed exit, exact death and native restored custody could not be proved; no item was changed.");
return;
}
if (transitioning.putIfAbsent(attempt.owner, attempt) != null) return;
attempt.completedDeathRead = true;
// Character work may outlive this Player. A new arrival is never allowed to publish
// through a stale callback, and the original owner's outstanding claim is retained.
persist(() -> characters.find(episode.character()).thenCompose(found -> {
if (found.isPresent() && deadFor(found.orElseThrow(), episode))
return finalConsequences(episode).thenApply(ignored -> found);
if (found.isPresent() && found.orElseThrow().dead())
return CompletableFuture.completedStage(Optional.empty());
return recordOfflineFinalDeath(episode);
}), (dead, failure) -> {
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
try {
if (failure != null) { diagnostic(attempt, failure); return; }
var currentDeath = unresolvedFinalDeath(attempt.owner);
if (dead == null || dead.isEmpty() || !deadFor(dead.orElseThrow(), episode)
|| closed || !attempt.player.isOnline() || currentDeath == null
|| !currentDeath.id().equals(episode.id())
|| transitioning.get(attempt.owner) != attempt
|| owned.get(attempt.owner) != prior) return;
if (!unchangedRecovery(attempt) || resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
var liveMarker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (liveMarker == null || !liveMarker.matches(episode.session(), episode.character())
|| liveMarker.phase() != EquipmentSessionMarker.Phase.RESTORED
|| hasRemnants(attempt.player)) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"Completed exit or exact saved sheet changed before Tail delivery; no item was changed.");
return;
}
if (prior != null && prior.player == attempt.player) {
retryTail(attempt.player, prior);
return;
}
var current = attempt.player.getInventory().getItemInOffHand();
var existing = tails.identify(current).orElse(null);
if (existing != null) {
if (existing.characterId().equals(episode.character()) && existing.deathId().equals(episode.id()))
publishRecoveredDowned(episode);
return;
}
if (!sheets.authorizes(current, dead.orElseThrow())) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"The current sheet does not match the saved death; no item was changed.");
return;
}
attempt.defeated = true;
attempt.finalDowned = episode;
attempt.deathResolved = true;
attempt.deathRecord = dead.orElseThrow();
attempt.gearAcknowledged = true;
attempt.partyDefeatAcknowledged = true;
attempt.session = episode.session();
attempt.character = episode.character();
attempt.claim = prior == null ? null : prior.claim;
owned.put(attempt.owner, attempt);
if (prior != null) prior.deliveryInvalidated = true;
attempt.deathReference = copy(current);
attempt.deathNativeReference = nativeIdentity(current);
attempt.deathView = attempt.player.getOpenInventory();
if (returnRecoveredDeath(attempt, episode)) deliverTail(attempt, dead.orElseThrow());
} finally {
transitioning.remove(attempt.owner, attempt);
finishDrain();
}
}
});
} catch (RuntimeException rejected) {
transitioning.remove(attempt.owner, attempt);
diagnostic(attempt, rejected);
finishDrain();
}
});
}
private void publishRecoveredDowned(DownedEpisode episode){
var current = unresolvedFinalDeath(episode.player());
if(closed || current == null || !current.id().equals(episode.id()))return;
if(downedEvents!=null)downedEvents.outcomePublished(episode);
downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((published,failure)->{
synchronized(EquipmentSessions.this){
if(failure!=null)diagnostic(new Failure(episode.player(),episode.session(),failure));
else if(!closed&&downedEvents!=null)downedEvents.outcomePublished(published);
}
});
}
/** 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;
}
/** The exact view closed by this plugin's defeat-return teleport may be rebound after teleport. */
public synchronized void invalidateTail(UUID owner, org.bukkit.inventory.InventoryView closedView) {
var attempt = owned.get(owner);
if (attempt == null || !attempt.defeated) return;
if (attempt.defeatReturnTeleport && attempt.deathView == closedView) {
attempt.deathView = null;
return;
}
attempt.deliveryInvalidated = true;
}
private void queueTail(Attempt attempt) {
// Persistence callbacks may enqueue immutable authority; native online/view/item checks
// belong to deliverTail on the owner thread, never the receipt/death worker.
if (closed || owned.get(attempt.owner) != attempt
|| attempt.tailCallbackQueued || attempt.bookAttempted || attempt.bookDelivered
|| attempt.deliveryInvalidated || !attempt.deathResolved || !attempt.partyDefeatAcknowledged
|| !attempt.gearAcknowledged || attempt.deathRecord == null) return;
attempt.tailCallbackQueued = true;
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
attempt.tailCallbackQueued = false;
deliverTail(attempt, attempt.deathRecord);
}
});
} catch (RuntimeException error) {
attempt.tailCallbackQueued = false;
conversionNotStarted(attempt, "Tail callback was rejected before its native write ("
+ error.getClass().getSimpleName() + ")");
}
}
private void retryTail(Player player, Attempt attempt) {
if (attempt.player != player || !player.isOnline() || attempt.bookAttempted || attempt.bookDelivered
|| attempt.deliveryInvalidated || !tailCustody(attempt)) {
attempt.deliveryInvalidated = true;
notice(attempt.owner, "DEFEAT_INSPECTION_REQUIRED",
"Death or Tail custody is ambiguous; items were retained for administrator inspection.");
return;
}
if (!attempt.deathResolved || !attempt.partyDefeatAcknowledged || !attempt.gearAcknowledged
|| attempt.deathRecord == null) {
notice(attempt.owner, "DEFEAT_PENDING",
"Death persistence, restoration or Tail prerequisites are still pending; no item was changed.");
return;
}
attempt.tailCallbackQueued = false;
deliverTail(attempt, attempt.deathRecord);
}
private void deliverTail(Attempt attempt, CharacterRecord dead) {
if (owned.get(attempt.owner) != attempt || attempt.bookAttempted || attempt.bookDelivered) return;
try {
if (attempt.finalDowned != null && (!attempt.deathResolved || !attempt.partyDefeatAcknowledged
|| !attempt.gearAcknowledged || !deadFor(dead, attempt.finalDowned)
|| !deathProof(attempt, unresolvedFinalDeath(attempt.owner)))) {
conversionUncertain(attempt, "Exact final-death prerequisites were not acknowledged before Tail delivery");
return;
}
if (!tailContext(attempt) || !tailCustody(attempt)) {
conversionUncertain(attempt, "Tail destination/context is stale or equipment restoration is unresolved"); return;
}
// Constructing a book cannot mutate native inventory and remains retryable if it fails.
var book = new games.dmg.fantasystick.items.TailBooks().create(dead);
attempt.bookAttempted = true; // From this point an exception may follow a native write; never replay.
// 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.
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;
publishDowned(attempt.finalDowned,attempt);
release(attempt);
sync(attempt);
} catch (RuntimeException failure) {
if (attempt.bookAttempted) {
diagnostic(attempt, failure);
conversionUncertain(attempt, "Tail native write failed or is uncertain; never replay");
} else conversionNotStarted(attempt, "Tail construction failed before its native write ("
+ failure.getClass().getSimpleName() + ")");
}
}
private void publishDowned(DownedEpisode episode,Attempt attempt){if(episode==null||episode.published()||downedDirectory==null)return;if(downedEvents!=null)downedEvents.outcomePublished(episode);downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((published,failure)->{if(failure!=null)diagnostic(attempt,failure);else if(downedEvents!=null)downedEvents.outcomePublished(published);});}
private boolean tailCustody(Attempt attempt) {
var current = attempt.player.getInventory().getItemInOffHand();
var authority = attempt.deathRecord == null ? attempt.record : attempt.deathRecord;
return attempt.deathReference != null && attempt.deathNativeReference != null
&& Objects.equals(attempt.deathReference, copy(current))
&& nativeIdentity(current) == attempt.deathNativeReference
&& authority != null && sheets.authorizes(attempt.deathReference, authority)
&& attempt.deathReference.getAmount() >= 1
&& attempt.deathReference.getAmount() <= attempt.deathReference.getMaxStackSize();
}
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 conversionNotStarted(Attempt attempt, String reason) {
diagnostic(attempt, new IllegalStateException(reason + "; character " + attempt.character
+ ". The exact same-lifetime retained sheet may retry after acknowledged prerequisites."));
}
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;
if(sessionEvents!=null)sessionEvents.forget(attempt.owner,attempt.session);
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) {
if(switchEvents!=null&&attempt.switchExit==null&&attempt.record!=null)
attempt.switchExit=switchEvents.exit(attempt.player,attempt.session,attempt.record,attempt.exitReason);
if(sessionEvents!=null&&attempt.exitEvent==null&&!attempt.defeated&&attempt.downed==null&&!closed&&attempt.player.isOnline()&&attempt.record!=null)
attempt.exitEvent=sessionEvents.captureExit(attempt.player,attempt.session,attempt.record,attempt.entryLocation);
captureExitDelay(attempt);
if (nutritionPolicy != null) nutritionPolicy.flushNativeHealing(attempt.player);
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);
if (equipmentEvents != null) attempt.restoreAction = equipmentEvents.action(
attempt.player, attempt.session, attempt.character, "equipment_restore");
EquipmentStorage.RestoreResult result;
try {
result = restoreMarked(attempt);
} catch (RuntimeException failure) {
attempt.nativeUncertain = true;
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.restoreAction, "uncertain", "native_exception");
if (attempt.recoveryAction != null) {
equipmentEvents.resolved(attempt.recoveryAction, "uncertain", "native_exception");
equipmentEvents.recovery(attempt.recoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, "restoring", "native_uncertain", "ambiguous",
"native_exception", attempt.recoveryReceiptRevision);
}
}
captureRecoveryLocations(attempt);
sessionReconciled(attempt, "restoring", "ambiguous", "native_uncertain",
"native_exception", attempt.recoveryReceiptRevision);
restoreVitals(attempt); // Proven health ownership is independent of uncertain equipment writes.
captureRecoveryLocations(attempt);
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);
attempt.restorationRefused = result != EquipmentStorage.RestoreResult.RESTORED;
if (result == EquipmentStorage.RestoreResult.RESTORED && (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged)) {
attempt.gearRestoredForModeRecovery = true;
}
captureRecoveryLocations(attempt);
if (result == EquipmentStorage.RestoreResult.RESTORED && attempt.defeated && attempt.deathReference == null) {
var retained = attempt.player.getInventory().getItemInOffHand();
attempt.deathReference = copy(retained);
attempt.deathNativeReference = nativeIdentity(retained);
attempt.deathView = attempt.player.getOpenInventory();
}
persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED && modeRestored && vitalsRestored);
if (result != EquipmentStorage.RestoreResult.RESTORED) {
if (equipmentEvents != null) {
var reason = result.name().toLowerCase(java.util.Locale.ROOT);
equipmentEvents.resolved(attempt.restoreAction, "refused", reason);
if (attempt.recoveryAction != null) equipmentEvents.resolved(attempt.recoveryAction, "retained", reason);
if (attempt.recoveryAction != null) equipmentEvents.recovery(attempt.recoveryAction,
attempt.session, attempt.character, attempt.recoveryPriorPhase, "pending",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"retained", reason, attempt.recoveryReceiptRevision);
}
sessionReconciled(attempt, "pending", "retained", "receipt_and_marker_only",
result.name().toLowerCase(java.util.Locale.ROOT), attempt.recoveryReceiptRevision);
notice(attempt.owner, result.name(), "Equipment recovery refused: " + result);
} else {
if ((!modeRestored || !vitalsRestored) && equipmentEvents != null) {
equipmentEvents.resolved(attempt.restoreAction, "pending", "receipt_incomplete");
equipmentEvents.resolved(attempt.recoveryAction, "pending", "receipt_incomplete");
}
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;
}
if (equipmentEvents != null && attempt.restoreEvent == null) try {
equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).ifPresent(box -> {
var head = attempt.player.getInventory().getItem(39);
boolean displaced = box.displacedHead() && !controls.owned(head, attempt.owner, attempt.session)
&& (gear == null || !gear.owned(head, attempt.owner, attempt.session));
attempt.restoreEvent = equipmentEvents.capture(attempt.player, attempt.session,
attempt.character, attempt.record == null ? null : attempt.record.name(),
new EquipmentStorage.Snapshot(box.boxSource(), box.boxSlot(), box.hotbarSlots(),
box.armorSlots(), displaced));
});
} catch (RuntimeException observationFailure) { diagnostic(attempt, observationFailure); }
mark(attempt, EquipmentSessionMarker.Phase.RESTORING);
var result = equipment.restore(attempt.player.getInventory(), attempt.owner, attempt.session,
item -> controls.owned(item, attempt.owner, attempt.session)||(gear!=null&&gear.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.downing||attempt.downed!=null){attempt.healthAcknowledged=true;return;}
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"));
attempt.healthSaveFailed = true;
if (attempt.nativeRestored) recoveryIncomplete(attempt, "health_unverified");
return;
}
attempt.healthAcknowledged = true;
if (attempt.nativeRestored) persistExit(attempt, true);
});
} catch (RuntimeException failure) {
attempt.healthSaveFailed = true;
diagnostic(attempt, failure);
}
}
private void recoveryIncomplete(Attempt attempt, String reason) {
if (attempt.recoveryResolved && attempt.sessionRecoveryResolved) return;
nutritionRetained(attempt, reason);
if (equipmentEvents != null && attempt.recoveryAction != null && !attempt.recoveryResolved) {
attempt.recoveryResolved = true;
equipmentEvents.recovery(attempt.recoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, "restored", "native_restored_receipt_pending",
"ambiguous", reason, attempt.recoveryReceiptRevision);
}
sessionReconciled(attempt, "restored", "ambiguous", "native_restored_receipt_pending",
reason, attempt.recoveryReceiptRevision);
}
private void captureRecoveryLocations(Attempt attempt) {
if (sessionRecoveryEvents == null || attempt.sessionRecoveryAction == null) return;
attempt.recoveryOriginalLocation = sessionRecoveryEvents.captureLocation(attempt.entryLocation);
attempt.recoveryCurrentLocation = sessionRecoveryEvents.captureLocation(attempt.player.getLocation());
}
private void adminRecoveryResult(Attempt attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome outcome,
String reason) {
if (adminAudit == null || attempt.adminRecoveryAction == null) return;
var facts = new java.util.LinkedHashMap<String, Object>();
if (attempt.sessionRecoveryAction != null) facts.put("domain_operation_id", attempt.sessionRecoveryAction.id());
if (attempt.character != null) facts.put("subject_id", attempt.character);
adminAudit.result(attempt.adminRecoveryAction, outcome, reason, facts);
}
private void sessionReconciled(Attempt attempt, String phase, String outcome, String quality,
String reason, java.math.BigInteger revision) {
if (attempt.sessionRecoveryResolved
|| (sessionRecoveryEvents == null || attempt.sessionRecoveryAction == null)
&& attempt.adminRecoveryAction == null) return;
attempt.sessionRecoveryResolved = true;
try {
if (sessionRecoveryEvents != null && attempt.sessionRecoveryAction != null)
sessionRecoveryEvents.reconciled(attempt.sessionRecoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, phase, outcome, quality, reason, attempt.recoveryReceiptRevision,
revision, attempt.recoveryAction == null ? null : attempt.recoveryAction.id(),
attempt.recoveryOriginalLocation, attempt.recoveryCurrentLocation);
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
adminRecoveryResult(attempt, switch (outcome) {
case "restored" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED;
case "failed" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED;
case "retained" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED;
default -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN;
}, switch (outcome) {
case "restored" -> "acknowledged";
case "failed" -> "operation_failed";
case "retained" -> "owner_refused";
default -> "operation_uncertain";
});
}
private void nutritionRetained(Attempt attempt, String reason) {
if (nutritionEvents == null || attempt.ordinaryVitals == null || attempt.nutritionRetainedWritten) return;
var captured = attempt.nutritionBeforeRestore == null
? nutritionEvents.capture(attempt.player, attempt.session, attempt.character,
attempt.record == null ? null : attempt.record.name(), attempt.exitReason)
: attempt.nutritionBeforeRestore;
if (captured == null) return;
attempt.nutritionRetainedWritten = true;
nutritionEvents.restorationRetained(captured, reason);
}
private boolean restoreVitals(Attempt attempt) {
if (vitals == null || attempt.ordinaryVitals == null) return true;
boolean applied = nutritionEvents != null && vitals.nutritionRestorationReady(
attempt.player, attempt.session, attempt.ordinaryVitals);
var before = nutritionEvents == null ? null : nutritionEvents.capture(attempt.player,
attempt.session, attempt.character, attempt.record == null ? null : attempt.record.name(), attempt.exitReason);
try {
if (vitals.restore(attempt.player, attempt.session, attempt.ordinaryVitals)) {
if (applied && before != null) {
attempt.nutritionBeforeRestore = before;
attempt.nutritionAfterRestore = nutritionEvents.capture(attempt.player, attempt.session,
attempt.character, attempt.record == null ? null : attempt.record.name(), attempt.exitReason);
}
return true;
}
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
nutritionRetained(attempt, "native_restoration_unverified");
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) -> {
if (attempt.finalDowned == null) {
exitAcknowledged(attempt, complete, state, failure);
return;
}
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
exitAcknowledged(attempt, complete, state, failure);
}
});
} catch (RuntimeException rejected) {
attempt.saving = false;
attempt.receiptUncertain = true;
conversionUncertain(attempt, "Native death acknowledgement scheduling was refused; retain completed receipt and custody");
diagnostic(attempt, rejected);
}
});
}
/** Final-death acknowledgment is handed back to the native owner before item/view validation. */
private void exitAcknowledged(Attempt attempt, boolean complete, EquipmentSessionStore.State state, Throwable failure) {
attempt.saving = false;
if (failure != null) {
if (attempt.defeated) attempt.receiptUncertain = true;
nutritionRetained(attempt, "receipt_save_failed");
sessionReconciled(attempt,
attempt.nativeRestored ? "restored" : "pending",
attempt.nativeRestored ? "ambiguous" : "failed",
attempt.nativeRestored ? "native_restored_receipt_pending" : "receipt_unavailable",
"receipt_save_failed", attempt.recoveryReceiptRevision);
diagnostic(attempt, failure);
if (attempt.defeated) conversionUncertain(attempt,
"Equipment restoration persistence failed before Tail conversion");
} else if (complete && attempt.finalDowned != null && (closed || owned.get(attempt.owner) != attempt
|| !attempt.player.isOnline() || state.pending() != null || state.lastExit() == null
|| !state.lastExit().sessionId().equals(attempt.session)
|| !state.lastExit().characterId().equals(attempt.character)
|| attempt.deathResolved && !deathProof(attempt, unresolvedFinalDeath(attempt.owner))
|| !tailContext(attempt) || !tailCustody(attempt))) {
conversionUncertain(attempt, "Native death custody changed before receipt acknowledgement; completion is not Tail authority");
} else if (complete) {
attempt.gearAcknowledged = true;
if (!attempt.restoreEventWritten && equipmentEvents != null && attempt.restoreEvent != null) {
attempt.restoreEventWritten = true;
equipmentEvents.restored(attempt.restoreEvent, state.revision());
}
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.restoreAction, "accepted", "receipt_completed");
if (attempt.recoveryAction != null && !attempt.recoveryResolved) {
attempt.recoveryResolved = true;
equipmentEvents.resolved(attempt.recoveryAction, "accepted", "receipt_completed");
equipmentEvents.recovery(attempt.recoveryAction,
attempt.session, attempt.character, attempt.recoveryPriorPhase, "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"restored", "receipt_completed", state.revision());
}
}
sessionReconciled(attempt, "restored", "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"receipt_completed", state.revision());
if (!attempt.switchEventWritten && switchEvents != null) {
attempt.switchEventWritten = true;
switchEvents.started(attempt.switchExit, state);
}
if (!attempt.nutritionRestoreWritten && nutritionEvents != null
&& attempt.nutritionAfterRestore != null) {
attempt.nutritionRestoreWritten = true;
nutritionEvents.restored(attempt.nutritionBeforeRestore, attempt.nutritionAfterRestore,
attempt.ordinaryVitals, state.revision());
}
if (!attempt.defeated && !attempt.exitEventWritten && attempt.exitEvent != null && sessionEvents != null) {
attempt.exitEventWritten = true;
sessionEvents.exited(attempt.session,attempt.exitEvent);
}
if (attempt.defeated) queueTail(attempt);
release(attempt);
} else {
nutritionRetained(attempt, !attempt.healthAcknowledged ? "health_unverified" : "receipt_incomplete");
if (attempt.defeated) {
if (attempt.restorationRefused)
conversionNotStarted(attempt, "Equipment restoration was refused; receipt and Tail custody retained");
else conversionUncertain(attempt,
"Equipment restoration was not acknowledged; Tail conversion remains unsafe");
}
}
}
/** A synchronous exit request is not proof of an acknowledged character/receipt restoration. */
public record DisableSummary(int entryRefused, int exitRequested, int nativeRestoredPendingReceipt,
int exitFailed, int exitPending) { }
/** Cancel pending activation and route every active player through ordinary restoration. */
public synchronized DisableSummary disableRoleplay() {
var pendingEntries = java.util.List.copyOf(pending.values());
var activeSessions = java.util.List.copyOf(active.values());
for (var attempt : pendingEntries) {
refuse(attempt, "ROLEPLAY_DISABLED", "Fantasy roleplaying was disabled before activation completed.");
}
int nativeRestored = 0, failed = 0;
for (var attempt : activeSessions) {
try {
var result = exit(attempt.player);
if (result == EquipmentStorage.RestoreResult.RESTORED) nativeRestored++;
else if (result != EquipmentStorage.RestoreResult.NOT_FOUND) failed++;
} catch (RuntimeException uncertain) {
diagnostic(attempt, uncertain);
failed++;
}
}
return new DisableSummary(pendingEntries.size(), activeSessions.size(), nativeRestored,
failed, activeSessions.size() - failed);
}
public synchronized void cancelEntry(UUID player) {
var attempt = pending.remove(player);
if (attempt != null) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
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()))
|| attempt.sheetIdentity != null && !attempt.sheetIdentity.equals(
sheets.identity(attempt.player.getInventory().getItemInOffHand()).orElse(null))) {
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) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
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) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
return;
}
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
try { callback.run(); }
catch (RuntimeException failure) { fail(attempt, failure); }
}
});
} catch (RuntimeException failure) { fail(attempt, failure); }
}
private static Object nativeIdentity(ItemStack item) {
return item == null || item.isEmpty() ? null : org.bukkit.craftbukkit.inventory.CraftItemStack.unwrap(item);
}
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, null, null); }
public synchronized void recover(Player player, games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action) {
recover(player, false, action, null);
}
/** The command's captured action is carried across receipt I/O, not rediscovered from a callback thread. */
public synchronized void recover(Player player, games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action,
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminAction) {
recover(player, false, action, adminAction);
}
/** Read the receipt before considering any historical no-pending-receipt Tail delivery. */
public synchronized void arrive(Player player) { recover(player, true, null, null); }
private void recover(Player player, boolean arrival,
games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action,
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminAction) {
UUID owner = player.getUniqueId();
invalidateCursor(owner);
var refused = new Attempt(player, owner, null);
refused.sessionRecoveryAction = action;
refused.adminRecoveryAction = adminAction;
if (closed || !player.isOnline()) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
return;
}
var previous = owned.get(owner);
if (previous != null && previous.defeated && (previous.bookAttempted || previous.bookDelivered
|| !arrival && previous.gearAcknowledged)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
notice(owner, "DEFEAT_PENDING", "Death or Tail conversion is pending/uncertain; retained state requires inspection, not automatic replay."); return;
}
if (previous != null && (previous.nativeUncertain || previous.receiptUncertain)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain");
notice(owner, "NATIVE_UNCERTAIN", "An equipment or receipt 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)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
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;
attempt.snapshot = snapshot(player);
attempt.cursor = copy(player.getItemOnCursor());
attempt.entryMarker = EquipmentSessionMarker.read(player).orElse(null);
attempt.sessionRecoveryAction = action;
attempt.adminRecoveryAction = adminAction;
// 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 DownedEpisode unresolvedFinalDeath(UUID owner) {
return downedDirectory == null ? null : downedDirectory.all().stream()
.filter(value -> value.player().equals(owner) && value.phase() == DownedEpisode.Phase.RESOLVED
&& value.outcome() == DownedEpisode.Outcome.FINAL_DEATH && !value.published())
.findFirst().orElse(null);
}
private static boolean deadFor(CharacterRecord record, DownedEpisode episode) {
return record != null && episode != null && record.id().equals(episode.character())
&& record.dead() && episode.id().equals(record.deathId())
&& episode.resolvedAt().equals(record.diedAt());
}
private static boolean deathProof(Attempt previous, DownedEpisode episode) {
return episode != null && previous.finalDowned != null && previous.finalDowned.id().equals(episode.id())
&& previous.owner.equals(episode.player()) && previous.session.equals(episode.session())
&& previous.character.equals(episode.character()) && previous.deathResolved
&& deadFor(previous.deathRecord, episode);
}
private void retainRecovery(Attempt attempt, String reason) {
if (equipmentEvents != null) equipmentEvents.resolved(attempt.recoveryAction, "retained", reason);
sessionReconciled(attempt, "pending", "retained", "receipt_and_marker_only", reason,
attempt.recoveryReceiptRevision);
notice(attempt.owner, "DEFEAT_INSPECTION_REQUIRED", "Death or equipment custody is unproved ("
+ reason + "); the original receipt and native items were retained.");
}
private boolean unchangedRecovery(Attempt attempt) {
return Arrays.equals(attempt.snapshot, snapshot(attempt.player))
&& Objects.equals(attempt.cursor, copy(attempt.player.getItemOnCursor()))
&& Objects.equals(attempt.entryMarker, EquipmentSessionMarker.read(attempt.player).orElse(null));
}
private boolean packedDeathCustody(Attempt attempt, DownedEpisode episode) {
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
return attempt.session.equals(episode.session()) && attempt.character.equals(episode.character())
&& unchangedRecovery(attempt) && marker != null
&& marker.matches(attempt.session, attempt.character)
&& marker.phase() == EquipmentSessionMarker.Phase.PACKED
&& equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).isPresent();
}
/** A cold coordinator must continue the same death through restoration, receipt and Tail, on its first arrival. */
private void reconcilePendingDeath(Attempt attempt, DownedEpisode episode) {
if (!packedDeathCustody(attempt, episode) || resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "native_custody_unverified");
return;
}
if (transitioning.putIfAbsent(attempt.owner, attempt) != null) return;
attempt.completedDeathRead = true;
attempt.defeated = true;
attempt.finalDowned = episode;
attempt.exitReason = "defeat";
owned.put(attempt.owner, attempt);
persist(() -> characters.find(episode.character()).thenCompose(found -> {
if (found.isPresent() && deadFor(found.orElseThrow(), episode))
return finalConsequences(episode).thenApply(ignored -> found);
if (found.isPresent() && found.orElseThrow().dead())
return CompletableFuture.completedStage(Optional.empty());
return recordOfflineFinalDeath(episode);
}), (dead, failure) -> {
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
try {
if (failure != null) {
diagnostic(attempt, failure);
conversionUncertain(attempt, "Pending death persistence/consequences were not acknowledged");
return;
}
var currentDeath = unresolvedFinalDeath(attempt.owner);
if (closed || !attempt.player.isOnline() || owned.get(attempt.owner) != attempt
|| transitioning.get(attempt.owner) != attempt || currentDeath == null
|| !currentDeath.id().equals(episode.id())) return;
if (dead == null || dead.isEmpty() || !deadFor(dead.orElseThrow(), episode)
|| !packedDeathCustody(attempt, episode)
|| resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
attempt.record = dead.orElseThrow();
attempt.deathRecord = attempt.record;
attempt.deathResolved = true;
attempt.partyDefeatAcknowledged = true; // Actual consequence future succeeded.
attempt.recoveryPriorPhase = "packed";
if (restoreExit(attempt) == EquipmentStorage.RestoreResult.RESTORED)
returnRecoveredDeath(attempt, episode);
} finally {
transitioning.remove(attempt.owner, attempt);
finishDrain();
}
}
});
} catch (RuntimeException rejected) {
transitioning.remove(attempt.owner, attempt);
conversionUncertain(attempt, "Pending death native scheduling was refused");
diagnostic(attempt, rejected);
finishDrain();
}
});
}
/** Transfer the original claim and death authority only after current-Player proof, not on UUID alone. */
private Attempt rebindDeath(Attempt previous, Attempt rebound) {
rebound.claim = previous.claim;
rebound.record = previous.record;
rebound.deathRecord = previous.deathRecord;
rebound.finalDowned = previous.finalDowned;
rebound.deathResolved = previous.deathResolved;
rebound.partyDefeatAcknowledged = previous.partyDefeatAcknowledged;
rebound.defeated = true;
rebound.exitReason = previous.exitReason;
rebound.entryLocation = previous.entryLocation;
rebound.exitDelay = previous.exitDelay;
rebound.healthAcknowledged = previous.healthAcknowledged;
rebound.switchExit = previous.switchExit;
rebound.switchEventWritten = previous.switchEventWritten;
rebound.nutritionRestoreWritten = previous.nutritionRestoreWritten;
rebound.nutritionRetainedWritten = previous.nutritionRetainedWritten;
rebound.nutritionBeforeRestore = previous.nutritionBeforeRestore;
rebound.nutritionAfterRestore = previous.nutritionAfterRestore;
rebound.gearRestoredForModeRecovery = false; // Never inherit same-Player native proof.
rebound.recoveryPriorPhase = EquipmentSessionMarker.read(rebound.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
previous.deliveryInvalidated = true;
owned.put(rebound.owner, rebound);
return rebound;
}
private synchronized void recovered(Attempt attempt, Optional<EquipmentSessionStore.State> state, Throwable failure) {
if (!current(attempt)) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain");
return;
}
pending.remove(attempt.owner, attempt);
if (!attempt.player.isOnline()) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
return;
}
if (owned.get(attempt.owner) != attempt.recoveryOwner) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "stale");
notice(attempt.owner, "STALE_RECOVERY", "Session ownership changed after the recovery read; no old receipt was replayed.");
return;
}
if (failure != null) {
if (sessionRecoveryEvents != null) {
var action = attempt.sessionRecoveryAction == null
? sessionRecoveryEvents.system(attempt.player) : attempt.sessionRecoveryAction;
sessionRecoveryEvents.reconciled(action, null, null, "unavailable", "unavailable",
"failed", "receipt_unreadable", "receipt_read_failed", null, null, null, null,
sessionRecoveryEvents.captureLocation(attempt.player.getLocation()));
}
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed");
diagnostic(attempt, failure); return;
}
var receipt = state.map(EquipmentSessionStore.State::pending).orElse(null);
if (receipt == null) {
if (attempt.arrival) {
var death = unresolvedFinalDeath(attempt.owner);
if (death != null) {
reconcileCompletedDeath(attempt, state.orElse(null), death);
return;
}
var arrivingOwner = attempt.owner;
var episode=downedDirectory==null?null:downedDirectory.all().stream().filter(value->value.player().equals(arrivingOwner)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player,episode);
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.
}
if (equipmentEvents != null) equipmentEvents.resolved(
equipmentEvents.action(attempt.player, null, null, "equipment_recovery"), "refused", "no_receipt");
if (sessionRecoveryEvents != null) {
var action = attempt.sessionRecoveryAction == null
? sessionRecoveryEvents.system(attempt.player) : attempt.sessionRecoveryAction;
sessionRecoveryEvents.reconciled(action, null, null, "absent", "absent", "refused",
"receipt_missing", "no_receipt", null, null, null, null,
sessionRecoveryEvents.captureLocation(attempt.player.getLocation()));
}
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "not_found");
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.recoveryReceiptRevision = state.orElseThrow().revision();
if (sessionRecoveryEvents != null && attempt.sessionRecoveryAction == null)
attempt.sessionRecoveryAction = sessionRecoveryEvents.system(attempt.player);
if (equipmentEvents != null) attempt.recoveryAction = equipmentEvents.action(
attempt.player, attempt.session, attempt.character,
attempt.arrival ? "equipment_arrival_recovery" : "equipment_recovery");
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);
var savedDeath = unresolvedFinalDeath(attempt.owner);
if (savedDeath != null && (!attempt.session.equals(savedDeath.session())
|| !attempt.character.equals(savedDeath.character()) || !unchangedRecovery(attempt))) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
if (previous == null && attempt.arrival && savedDeath != null) {
reconcilePendingDeath(attempt, savedDeath);
return;
}
if (previous != null && !attempt.session.equals(previous.session)) {
if (equipmentEvents != null) equipmentEvents.resolved(attempt.recoveryAction, "refused", "session_mismatch");
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "stale");
notice(attempt.owner, "SESSION_MISMATCH", "Saved and process-local sessions disagree; items were left unchanged."); return;
}
if (previous != null && (previous.defeated || previous.vitalsStarted)) {
if (previous.finalDowned != null && !deathProof(previous, unresolvedFinalDeath(attempt.owner))) {
retainRecovery(attempt, "death_unverified");
return;
}
if (previous.player != attempt.player) {
// Never use a same-UUID obsolete Player's inventory or its native identity as
// custody proof. Rebind only after inspecting the current Player's PACKED box.
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (!previous.defeated || previous.finalDowned == null || previous.saving || !previous.deathResolved
|| !previous.partyDefeatAcknowledged
|| marker == null || !marker.matches(attempt.session, attempt.character)
|| marker.phase() != EquipmentSessionMarker.Phase.PACKED
|| equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).isEmpty()) {
retainRecovery(attempt, "native_custody_unverified");
return;
}
attempt = rebindDeath(previous, attempt);
} else {
// A refused same-Player restoration is retryable only while its first native
// write returned a definite refusal; an exception is never automatically replayed.
previous.recoveryAction = attempt.recoveryAction;
previous.sessionRecoveryAction = attempt.sessionRecoveryAction;
previous.adminRecoveryAction = attempt.adminRecoveryAction;
previous.recoveryReceiptRevision = attempt.recoveryReceiptRevision;
previous.recoveryPriorPhase = EquipmentSessionMarker.read(attempt.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
attempt = previous;
}
restoreExit(attempt);
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);
attempt.recoveryPriorPhase = EquipmentSessionMarker.read(attempt.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
try {
saveRemainingHealth(attempt);
boolean modeRestored = restoreGameMode(attempt);
var result = restoreMarked(attempt);
boolean vitalsRestored = restoreVitals(attempt);
captureRecoveryLocations(attempt);
if (result == EquipmentStorage.RestoreResult.RESTORED) {
if (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged) {
attempt.gearRestoredForModeRecovery = true;
if (equipmentEvents != null) {
var reason = !attempt.healthAcknowledged ? "health_unverified" : "native_restore_incomplete";
equipmentEvents.resolved(attempt.recoveryAction, "pending", reason);
if (attempt.healthSaveFailed || !modeRestored || !vitalsRestored)
recoveryIncomplete(attempt, reason);
}
}
persistExit(attempt, modeRestored && vitalsRestored);
sync(attempt);
} else {
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.recoveryAction, "retained", result.name().toLowerCase(java.util.Locale.ROOT));
equipmentEvents.recovery(attempt.recoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, "pending", "receipt_and_marker_only", "retained",
result.name().toLowerCase(java.util.Locale.ROOT), state.orElseThrow().revision());
}
sessionReconciled(attempt, "pending", "retained", "receipt_and_marker_only",
result.name().toLowerCase(java.util.Locale.ROOT), attempt.recoveryReceiptRevision);
notice(attempt.owner, result.name(), "Equipment recovery refused: " + result + "; receipt and items retained.");
}
} catch (RuntimeException error) {
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.recoveryAction, "uncertain", "native_exception");
equipmentEvents.recovery(attempt.recoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, "restoring", "native_uncertain", "ambiguous",
"native_exception", attempt.recoveryReceiptRevision);
}
captureRecoveryLocations(attempt);
sessionReconciled(attempt, "restoring", "ambiguous", "native_uncertain",
"native_exception", attempt.recoveryReceiptRevision);
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 : java.util.List.copyOf(transitioning.values())) {
if (attempt.completedDeathRead) {
transitioning.remove(attempt.owner, attempt);
continue; // No native mutation has begun; stale read callbacks must not publish.
}
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, "shutdown");
characterRecoveries.clear();
recoveryRecipients.clear();
claims.close();
} finally {
closeSweepFinished = true;
finishDrain();
}
}
}