feat(events): record downed combat outcomes
Release / release (push) Failing after 6m54s

This commit is contained in:
dmg committed 2026-09-24 08:51:44 -04:00
1 parent 1926dbb9f7
commit 819a966160
14 files changed
+615 -47

No files matched your search

@@ -163,6 +163,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
private games.dmg.fantasystick.passive.PassiveEngine passiveEngine;
private games.dmg.fantasystick.events.LocalEventLog eventLog;
private games.dmg.fantasystick.events.EventCaptureListener eventCapture;
private games.dmg.fantasystick.events.DownedEventBridge downedEvents;
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
@Override public void onEnable() {
@@ -696,9 +697,14 @@ public final class FantasyStickPlugin extends JavaPlugin {
getServer().getVersion(), getServer().getMinecraftVersion(), getDescription().getVersion()), 1024, 134_217_728L,
message -> getLogger().warning(message));
eventCapture = new games.dmg.fantasystick.events.EventCaptureListener(eventLog, sessions, Clock.systemUTC());
downedEvents = new games.dmg.fantasystick.events.DownedEventBridge(eventLog::emit, Clock.systemUTC());
sessions.attachDownedEvents(downedEvents);
downedController.attachEvents(downedEvents);
revive.attachDownedEvents(downedEvents);
admin.attachDownedEvents(downedEvents);
getServer().getPluginManager().registerEvents(eventCapture, this);
} catch (java.io.IOException failure) {
eventLog = null; eventCapture = null;
eventLog = null; eventCapture = null; downedEvents = null;
getLogger().log(Level.WARNING,"Fantasy Stick local events are unavailable; gameplay remains enabled",failure);
}
getServer().getPluginManager().registerEvents(crafting, this);
@@ -801,7 +807,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
combatFeedback = null;
var closingEvents = sessionEvents; sessionEvents = null;
var closingEventLog = eventLog; eventLog = null;
var closingEventCapture = eventCapture; eventCapture = null;
var closingEventCapture = eventCapture; eventCapture = null; downedEvents = null;
var closingBooks = books; books = null;
var closingPartyEvents = partyEvents; partyEvents = null;
var closingPartyCombat = partyCombat; partyCombat = null;
@@ -51,6 +51,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
private final TailBooks tails = new TailBooks();
private final CharacterSheets sheets = new CharacterSheets();
private games.dmg.fantasystick.session.DownedController downed;
private games.dmg.fantasystick.events.DownedEventBridge downedEvents;
private java.util.function.Supplier<Duration> downedProtection=()->Duration.ofSeconds(5);
private final Map<Inventory, View> inventories = new IdentityHashMap<>();
private final Map<UUID, View> targets = new LinkedHashMap<>();
@@ -83,6 +84,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
}
public void attachDowned(games.dmg.fantasystick.session.DownedController controller,java.util.function.Supplier<Duration> protection){if(closed||downed!=null)throw new IllegalStateException("Downed Revive already attached or closed");downed=Objects.requireNonNull(controller);downedProtection=Objects.requireNonNull(protection);}
public void attachDownedEvents(games.dmg.fantasystick.events.DownedEventBridge events){if(closed||downedEvents!=null)throw new IllegalStateException("Downed Revive events already attached or closed");downedEvents=Objects.requireNonNull(events);}
public AbilityDefinition definition() {
return new AbilityDefinition("revive", "Revive", Material.ECHO_SHARD,
@@ -104,7 +106,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
execution.input().player().sendMessage("Revive found no eligible player within 12 blocks and line of sight.");
execution.finish(); return;
}
if(downed!=null&&downed.downed(target)){downed.revive(target,downedProtection.get(),status->{execution.input().player().sendMessage(switch(status){case APPLIED->"Revive restored the downed character in place.";case EXPIRED->"Revive arrived after the downed countdown expired.";case STALE->"That downed episode was already resolved or changed.";case FAILED->"Downed Revive is pending recovery; no second rescue was attempted.";});execution.finish();});return;}
if(downed!=null&&downed.downed(target)){var episode=downedEpisode(target);if(episode==null){execution.finish();return;}var action=UUID.randomUUID();var caster=execution.character();var cooldown=caster.cooldowns().get("revive");var distance=execution.input().player().getLocation().distance(target.getLocation());var castAt=clock.instant();var decision=new games.dmg.fantasystick.session.DownedEpisode.Decision("revive",execution.input().player().getUniqueId(),execution.input().player().getName(),caster.id(),caster.name(),execution.input().session().session(),action,castAt,cooldown,distance,true);if(downedEvents!=null)downedEvents.abilityCast(episode,decision);downed.revive(target,downedProtection.get(),decision,status->{if(downedEvents!=null&&status!=games.dmg.fantasystick.session.DownedController.RescueStatus.APPLIED&&status!=games.dmg.fantasystick.session.DownedController.RescueStatus.APPLIED_PENDING_RECOVERY)downedEvents.abilityResolved(episode,decision,status.name().toLowerCase(java.util.Locale.ROOT),clock.instant());execution.input().player().sendMessage(switch(status){case APPLIED->"Revive restored the downed character in place.";case APPLIED_PENDING_RECOVERY->"Revive restored the downed character; durable publication is pending recovery.";case EXPIRED->"Revive arrived after the downed countdown expired.";case STALE->"That downed episode was already resolved or changed.";case FAILED->"Downed Revive is pending recovery; no second rescue was attempted.";});execution.finish();});return;}
var captured = candidates(target);
if (captured.isEmpty()) {
execution.input().player().sendMessage("That player has no direct-inventory Tail eligible for Revive.");
@@ -131,6 +133,8 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
}));
}
private games.dmg.fantasystick.session.DownedEpisode downedEpisode(Player target){return downed==null?null:downed.episode(target);}
private Player target(ControlInput input) {
Player caster = input.player();
Entity supplied = input.target();
@@ -0,0 +1,264 @@
package games.dmg.fantasystick.events;
import games.dmg.fantasystick.session.DownedEpisode;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
/** Failure-isolated event adapter for durable downed, rescue, death and protection boundaries. */
public final class DownedEventBridge {
private final Consumer<EventInput> sink;
private final Clock clock;
public DownedEventBridge(Consumer<EventInput> sink, Clock clock) {
this.sink = Objects.requireNonNull(sink);
this.clock = Objects.requireNonNull(clock);
}
/** Re-emits stable IDs from durable proof; at-least-once consumers deduplicate by source and ID. */
public void reconcile(Collection<DownedEpisode> episodes) {
for (var episode : List.copyOf(episodes)) {
downed(episode);
if (episode.phase() != DownedEpisode.Phase.RESOLVED) continue;
if (episode.decision() != null && "revive".equals(episode.decision().source())) {
abilityCast(episode, episode.decision());
}
resolved(episode);
if (episode.decision() != null && "revive".equals(episode.decision().source())) {
abilityResolved(episode);
}
if (episode.outcome() == DownedEpisode.Outcome.FINAL_DEATH && episode.published()) {
finalDeathRecorded(episode);
}
if (episode.published()) outcomePublished(episode);
if (episode.outcome() == DownedEpisode.Outcome.REVIVED && episode.protectionUntil() != null
&& !clock.instant().isBefore(episode.protectionUntil())) protectionEnded(episode);
}
}
public void downed(DownedEpisode episode) {
var data = common(episode);
data.put("stage", "acknowledged");
data.put("outcome", "downed");
emit(stable(episode.id(), "downed"), episode.id(), episode.downedAt(), "character.downed", data);
}
public void resolved(DownedEpisode episode) {
if (episode.phase() != DownedEpisode.Phase.RESOLVED) return;
var data = common(episode);
String outcome = decisionSource(episode);
data.put("stage", "decision_acknowledged");
data.put("outcome", outcome);
data.put("resolved_at", episode.resolvedAt());
data.put("publication_outcome", "pending");
if (episode.protectionUntil() != null) data.put("protection_until", episode.protectionUntil());
if (!episode.finalRewards().isEmpty()) {
data.put("final_rewards", episode.finalRewards().stream().map(reward -> Map.of(
"character_id", reward.character().toString(), "experience", reward.experience().toString(),
"coins", reward.coins().toString())).toList());
}
var decision = episode.decision();
if (decision != null) {
if (decision.actorPlayer() != null) {
data.put("actor_kind", "player");
data.put("actor_player_id", decision.actorPlayer().toString());
data.put("actor_player_name", decision.actorPlayerName());
}
if (decision.actorCharacter() != null) {
data.put("actor_character_id", decision.actorCharacter().toString());
data.put("actor_character_name", decision.actorCharacterName());
}
if (decision.actorSession() != null) data.put("actor_session_id", decision.actorSession().toString());
if (decision.actorCharacter() != null && !decision.actorCharacter().equals(episode.character())) {
data.put("actor_location_status", "unavailable");
}
if (decision.cooldownUntil() != null) data.put("cooldown_until", decision.cooldownUntil());
if (decision.finalRange() != null) data.put("final_range", decision.finalRange());
if (decision.lineOfSight() != null) data.put("line_of_sight", decision.lineOfSight());
}
emit(stable(episode.id(), "resolved"), episode.outcomeOperation(), episode.resolvedAt(),
"character.downed_resolved", actor(decision), data);
}
public void finalDeathRecorded(DownedEpisode episode) {
if (episode.outcome() != DownedEpisode.Outcome.FINAL_DEATH) return;
var data = common(episode);
data.put("stage", "death_recorded");
data.put("outcome", "acknowledged");
data.put("effective_death_time", episode.resolvedAt());
data.put("death_id", episode.id().toString());
data.put("tail_outcome", "pending");
data.put("return_outcome", "pending");
data.put("reward_outcome", "pending");
if (!episode.finalRewards().isEmpty()) {
data.put("final_rewards", episode.finalRewards().stream().map(reward -> Map.of(
"character_id", reward.character().toString(), "experience", reward.experience().toString(),
"coins", reward.coins().toString())).toList());
}
data.put("consequence_operation_id", episode.outcomeOperation().toString());
emit(stable(episode.id(), "died"), episode.outcomeOperation(), episode.resolvedAt(),
"character.died", data);
}
public void outcomePublished(DownedEpisode episode) {
var data = common(episode);
data.put("action_kind", episode.outcome() == DownedEpisode.Outcome.REVIVED
? "downed_revival_native_application" : "final_death_tail_delivery");
data.put("stage", "native_effect_acknowledged");
data.put("outcome", "completed");
emit(stable(episode.id(), "published"), episode.outcomeOperation(), episode.resolvedAt(),
"action.resolved", data);
}
public void prevented(DownedEpisode episode, String reason, double amount) {
if (!Double.isFinite(amount) || amount < 0) return;
var now = clock.instant();
var action = UUID.randomUUID();
var data = common(episode);
data.put("stage", "native_damage");
data.put("outcome", "prevented");
data.put("reason", Objects.requireNonNull(reason));
data.put("prevented_amount", Double.toString(amount));
emit(UUID.randomUUID(), action, now, "combat.prevented", data);
}
public void protectionEnded(DownedEpisode episode) {
if (episode.outcome() != DownedEpisode.Outcome.REVIVED || episode.protectionUntil() == null) return;
var data = common(episode);
data.put("effect_id", "revive_downed_invulnerability");
data.put("stage", "expiry");
data.put("outcome", "expired");
emit(stable(episode.id(), "protection-ended"), episode.outcomeOperation(), episode.protectionUntil(),
"effect.ended", data);
}
public void abilityCast(DownedEpisode episode, DownedEpisode.Decision decision) {
var data = common(episode);
data.put("actor_kind", "player");
data.put("ability_id", "revive");
data.put("stage", "cooldown_committed");
data.put("outcome", "accepted");
data.put("cooldown_until", decision.cooldownUntil());
data.put("actor_player_id", decision.actorPlayer().toString());
data.put("actor_character_id", decision.actorCharacter().toString());
data.put("actor_session_id", decision.actorSession().toString());
data.put("final_range", decision.finalRange());
data.put("line_of_sight", decision.lineOfSight());
emit(stable(decision.actionId(), "ability-cast"), decision.actionId(), decision.castAt(),
"ability.cast", actor(decision), data);
}
public void abilityResolved(DownedEpisode episode) {
var decision = episode.decision();
if (decision == null || !"revive".equals(decision.source())) return;
abilityResolved(episode, decision, "decision_won", episode.resolvedAt());
}
public void abilityResolved(DownedEpisode episode, DownedEpisode.Decision decision,
String outcome, Instant time) {
var data = common(episode);
if (decision != null && decision.actorPlayer() != null) {
data.put("actor_kind", "player");
data.put("actor_player_id", decision.actorPlayer().toString());
data.put("actor_character_id", decision.actorCharacter().toString());
data.put("actor_session_id", decision.actorSession().toString());
}
data.put("ability_id", "revive");
data.put("stage", "downed_target_resolution");
data.put("outcome", Objects.requireNonNull(outcome));
var actionId = decision == null ? episode.outcomeOperation() : decision.actionId();
emit(stable(actionId, "ability-resolved"), actionId, time, "ability.resolved", actor(decision), data);
}
public void configRead(String actorKind, UUID player, String playerName, String key, String value) {
config("config.read", actorKind, player, playerName, key, null, value);
}
public void configChanged(String actorKind, UUID player, String playerName, String key,
String before, String after) {
config("config.changed", actorKind, player, playerName, key, before, after);
}
private void config(String type, String actorKind, UUID player, String playerName, String key,
String before, String after) {
var now = clock.instant();
var action = UUID.randomUUID();
var data = new LinkedHashMap<String, Object>();
data.put("actor_kind", Objects.requireNonNull(actorKind));
if (player != null) data.put("actor_player_id", player.toString());
if (playerName != null) data.put("actor_player_name", playerName);
data.put("key", Objects.requireNonNull(key));
if (before != null) data.put("before", before);
data.put("after", Objects.requireNonNull(after));
data.put("application", "future_downed_outcomes");
data.put("outcome", "acknowledged");
EventInput.Context context=player==null?null:new EventInput.Context(player,playerName,null,null,null,null);
emit(UUID.randomUUID(), action, now, type, context, data);
}
private LinkedHashMap<String, Object> common(DownedEpisode episode) {
Objects.requireNonNull(episode);
var data = new LinkedHashMap<String, Object>();
data.put("actor_kind", "system");
data.put("episode_id", episode.id().toString());
data.put("subject_character_id", episode.character().toString());
if(episode.characterName()!=null)data.put("subject_character_name",episode.characterName());
data.put("subject_player_id", episode.player().toString());
if(episode.playerName()!=null)data.put("subject_player_name",episode.playerName());
data.put("custody_session_id", episode.session().toString());
data.put("custody", "active_or_recoverable_session");
if (episode.characterRevision() != null) data.put("character_revision", episode.characterRevision().toString());
data.put("downed_at", episode.downedAt());
data.put("deadline", episode.expiresAt());
data.put("lethal_cause", episode.attribution().cause());
if (episode.attribution().attacker() != null) {
data.put("lethal_source_id", episode.attribution().attacker().toString());
}
data.put("player_defeat", episode.attribution().playerDefeat());
data.put("contributors", episode.attribution().contributors().stream().map(UUID::toString).toList());
data.put("victim_level", Integer.toString(episode.attribution().victimLevel()));
data.put("victim_coins", episode.attribution().victimCoins().toString());
data.put("location", location(episode.world(), episode.x(), episode.y(), episode.z(), episode.downedAt()));
data.put("location_role", "downed_subject_anchor");
data.put("entry_return", location(episode.entryWorld(), episode.entryX(), episode.entryY(),
episode.entryZ(), episode.downedAt()));
return data;
}
private static Map<String, Object> location(UUID world, double x, double y, double z, Instant capturedAt) {
return Map.of("world_id", world.toString(), "x", Double.toString(x), "y", Double.toString(y),
"z", Double.toString(z), "captured_at", capturedAt, "quality", "durable_native_capture");
}
private static String decisionSource(DownedEpisode episode) {
if (episode.decision() != null) return episode.decision().source();
if (episode.outcome() == DownedEpisode.Outcome.REVIVED) return "revive";
return episode.resolvedAt().equals(episode.expiresAt()) ? "timeout" : "accept_death";
}
private static EventInput.Context actor(DownedEpisode.Decision decision){if(decision==null||decision.actorPlayer()==null)return null;return new EventInput.Context(decision.actorPlayer(),decision.actorPlayerName(),decision.actorCharacter(),decision.actorCharacterName(),decision.actorSession(),null);}
private static UUID stable(UUID authority, String kind) {
return UUID.nameUUIDFromBytes(("fantasystick:" + authority + ':' + kind)
.getBytes(StandardCharsets.UTF_8));
}
private void emit(UUID id, UUID action, Instant time, String type, Map<String, Object> data) {
emit(id,action,time,type,null,data);
}
private void emit(UUID id,UUID action,Instant time,String type,EventInput.Context context,Map<String,Object> data){
try {
sink.accept(new EventInput(id, action, time, type, context, data));
} catch (RuntimeException ignored) {
// Logging is observability only and cannot alter the durable gameplay decision.
}
}
}
@@ -18,24 +18,27 @@ import org.bukkit.plugin.Plugin;
/** Native freeze, bounded death decision menu and timeout publication for durable episodes. */
public final class DownedController implements Listener,AutoCloseable{
public enum RescueStatus{APPLIED,STALE,EXPIRED,FAILED}
public enum RescueStatus{APPLIED,APPLIED_PENDING_RECOVERY,STALE,EXPIRED,FAILED}
private record Holder(UUID episode)implements InventoryHolder{public Inventory getInventory(){return null;}}
private final Plugin plugin;private final EquipmentSessions sessions;private final DownedDirectory directory;private final Clock clock;private final Consumer<Throwable> failures;private final java.util.Map<UUID,Boolean> gravity=new java.util.HashMap<>();private final java.util.Set<UUID> revertingSlots=new java.util.HashSet<>();private org.bukkit.scheduler.BukkitTask pulse;private boolean closed;
private final Plugin plugin;private final EquipmentSessions sessions;private final DownedDirectory directory;private final Clock clock;private final Consumer<Throwable> failures;private final java.util.Map<UUID,Boolean> gravity=new java.util.HashMap<>();private final java.util.Set<UUID> revertingSlots=new java.util.HashSet<>();private final java.util.Set<UUID> endedProtection=new java.util.HashSet<>();private games.dmg.fantasystick.events.DownedEventBridge events;private org.bukkit.scheduler.BukkitTask pulse;private boolean closed;
public DownedController(Plugin plugin,EquipmentSessions sessions,DownedDirectory directory,Clock clock,Consumer<Throwable> failures){this.plugin=Objects.requireNonNull(plugin);this.sessions=Objects.requireNonNull(sessions);this.directory=Objects.requireNonNull(directory);this.clock=Objects.requireNonNull(clock);this.failures=Objects.requireNonNull(failures);}
public void install(){if(pulse!=null)throw new IllegalStateException("Downed controller already installed");pulse=plugin.getServer().getScheduler().runTaskTimer(plugin,this::pulse,20L,20L);for(var episode:directory.all()){if(episode.phase()==DownedEpisode.Phase.PENDING){if(clock.instant().isBefore(episode.expiresAt()))open(episode);else finalizeDeath(episode);}else if(episode.outcome()==DownedEpisode.Outcome.FINAL_DEATH&&!episode.published())sessions.finalizeDowned(episode);}}
public void attachEvents(games.dmg.fantasystick.events.DownedEventBridge events){if(pulse!=null||this.events!=null)throw new IllegalStateException("Downed events already attached or controller installed");this.events=Objects.requireNonNull(events);}
public void install(){if(pulse!=null)throw new IllegalStateException("Downed controller already installed");pulse=plugin.getServer().getScheduler().runTaskTimer(plugin,this::pulse,20L,20L);var existing=directory.all();if(events!=null)events.reconcile(existing);for(var episode:existing){if(episode.outcome()==DownedEpisode.Outcome.REVIVED&&episode.protectionUntil()!=null&&!clock.instant().isBefore(episode.protectionUntil()))endedProtection.add(episode.id());if(episode.phase()==DownedEpisode.Phase.PENDING){if(clock.instant().isBefore(episode.expiresAt()))open(episode);else finalizeDeath(episode,"timeout");}else if(episode.outcome()==DownedEpisode.Outcome.FINAL_DEATH&&!episode.published())sessions.finalizeDowned(episode);}}
public void open(DownedEpisode episode){if(closed||episode.phase()!=DownedEpisode.Phase.PENDING)return;var player=plugin.getServer().getPlayer(episode.player());if(player==null||!player.isOnline())return;freeze(player);var inventory=plugin.getServer().createInventory(new Holder(episode.id()),27,Component.text("Downed — "+remaining(episode)+"s"));inventory.setItem(11,item(Material.SKELETON_SKULL,"Accept Death",true));inventory.setItem(13,item(Material.GRAY_DYE,"Use Phoenix Down — unavailable",false));inventory.setItem(15,item(Material.GRAY_DYE,"Wait for Revive",false));player.openInventory(inventory);}
private static ItemStack item(Material material,String name,boolean action){var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(name));if(!action)meta.lore(java.util.List.of(Component.text("Waiting does not pause the countdown.")));item.setItemMeta(meta);return item;}
private long remaining(DownedEpisode episode){var remaining=java.time.Duration.between(clock.instant(),episode.expiresAt());if(remaining.isNegative()||remaining.isZero())return 0;return remaining.getSeconds()+(remaining.getNano()==0?0:1);}
private void pulse(){if(closed)return;for(var episode:directory.all()){if(episode.phase()!=DownedEpisode.Phase.PENDING)continue;if(!clock.instant().isBefore(episode.expiresAt()))finalizeDeath(episode);else{var player=plugin.getServer().getPlayer(episode.player());if(player!=null&&player.isOnline()){if(player.getOpenInventory().getTopInventory().getHolder() instanceof Holder holder&&holder.episode().equals(episode.id()))player.getOpenInventory().setTitle("Downed — "+remaining(episode)+"s");else open(episode);}}}}
public boolean downed(Player player){return sessions.downed(player.getUniqueId()).isPresent();}
private void pulse(){if(closed)return;for(var episode:directory.all()){if(episode.phase()!=DownedEpisode.Phase.PENDING){if(episode.outcome()==DownedEpisode.Outcome.REVIVED&&episode.protectionUntil()!=null&&!clock.instant().isBefore(episode.protectionUntil())&&endedProtection.add(episode.id())&&events!=null)events.protectionEnded(episode);continue;}if(!clock.instant().isBefore(episode.expiresAt()))finalizeDeath(episode,"timeout");else{var player=plugin.getServer().getPlayer(episode.player());if(player!=null&&player.isOnline()){if(player.getOpenInventory().getTopInventory().getHolder() instanceof Holder holder&&holder.episode().equals(episode.id()))player.getOpenInventory().setTitle("Downed — "+remaining(episode)+"s");else open(episode);}}}}
public boolean downed(Player player){return episode(player)!=null;}
public DownedEpisode episode(Player player){return sessions.downed(player.getUniqueId()).orElse(null);}
private void freeze(Player player){gravity.putIfAbsent(player.getUniqueId(),player.hasGravity());player.setGravity(false);player.setFallDistance(0);player.setVelocity(new org.bukkit.util.Vector());if(player.isInsideVehicle())player.leaveVehicle();}
private void release(Player player){var original=gravity.remove(player.getUniqueId());if(original!=null)player.setGravity(original);revertingSlots.remove(player.getUniqueId());}
public void revive(Player target,Duration protection,Consumer<RescueStatus> result){var episode=sessions.downed(target.getUniqueId()).orElse(null);if(episode==null){result.accept(RescueStatus.STALE);return;}directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,UUID.randomUUID(),protection).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);result.accept(RescueStatus.FAILED);return;}if(claim.status()==DownedDirectory.ClaimStatus.EXPIRED){result.accept(RescueStatus.EXPIRED);return;}if(claim.status()!=DownedDirectory.ClaimStatus.APPLIED){result.accept(RescueStatus.STALE);return;}var resolved=claim.episode().orElseThrow();sessions.reviveDowned(resolved,applied->{if(!applied){result.accept(RescueStatus.FAILED);return;}release(target);directory.publish(resolved.id(),resolved.outcomeOperation()).whenComplete((published,publishFailure)->schedule(()->{if(publishFailure!=null){report(publishFailure);result.accept(RescueStatus.FAILED);}else result.accept(RescueStatus.APPLIED);}));});}));}
private void finalizeDeath(DownedEpisode episode){java.util.List<DownedEpisode.Reward> rewards;try{rewards=sessions.finalRewards(episode);}catch(RuntimeException failure){report(failure);return;}directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),Duration.ZERO,rewards).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);return;}if(claim.status()==DownedDirectory.ClaimStatus.APPLIED){var player=plugin.getServer().getPlayer(episode.player());if(player!=null)release(player);sessions.finalizeDowned(claim.episode().orElseThrow());}}));}
@EventHandler(priority=EventPriority.HIGHEST)public void click(org.bukkit.event.inventory.InventoryClickEvent event){if(event.getWhoClicked() instanceof Player actor&&sessions.downed(actor.getUniqueId()).isPresent())event.setCancelled(true);if(!(event.getView().getTopInventory().getHolder() instanceof Holder holder))return;event.setCancelled(true);if(!(event.getWhoClicked() instanceof Player player)||event.getRawSlot()!=11)return;var episode=directory.all().stream().filter(value->value.id().equals(holder.episode())&&value.player().equals(player.getUniqueId())&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);if(episode!=null)finalizeDeath(episode);}
public void revive(Player target,Duration protection,Consumer<RescueStatus> result){revive(target,protection,null,result);}
public void revive(Player target,Duration protection,DownedEpisode.Decision decision,Consumer<RescueStatus> result){var episode=sessions.downed(target.getUniqueId()).orElse(null);if(episode==null){result.accept(RescueStatus.STALE);return;}var operation=decision==null?UUID.randomUUID():decision.actionId();directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,operation,decision,protection,java.util.List.of()).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);result.accept(RescueStatus.FAILED);return;}if(claim.status()==DownedDirectory.ClaimStatus.EXPIRED){result.accept(RescueStatus.EXPIRED);return;}if(claim.status()!=DownedDirectory.ClaimStatus.APPLIED){result.accept(RescueStatus.STALE);return;}var resolved=claim.episode().orElseThrow();if(events!=null){events.resolved(resolved);events.abilityResolved(resolved);}sessions.reviveDowned(resolved,applied->{if(!applied){result.accept(RescueStatus.FAILED);return;}release(target);if(events!=null)events.outcomePublished(resolved);directory.publish(resolved.id(),resolved.outcomeOperation()).whenComplete((published,publishFailure)->schedule(()->{if(publishFailure!=null){report(publishFailure);result.accept(RescueStatus.APPLIED_PENDING_RECOVERY);}else{if(events!=null)events.outcomePublished(published);result.accept(RescueStatus.APPLIED);}}));});}));}
private void finalizeDeath(DownedEpisode episode,String source){java.util.List<DownedEpisode.Reward> rewards;try{rewards=sessions.finalRewards(episode);}catch(RuntimeException failure){report(failure);return;}var operation=UUID.randomUUID();var decision=new DownedEpisode.Decision(source,"accept_death".equals(source)?episode.player():null,"accept_death".equals(source)?episode.playerName():null,"accept_death".equals(source)?episode.character():null,"accept_death".equals(source)?episode.characterName():null,"accept_death".equals(source)?episode.session():null,operation,null,null,null,null);directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,operation,decision,Duration.ZERO,rewards).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);return;}if(claim.status()==DownedDirectory.ClaimStatus.APPLIED){var resolved=claim.episode().orElseThrow();if(events!=null)events.resolved(resolved);var player=plugin.getServer().getPlayer(episode.player());if(player!=null)release(player);sessions.finalizeDowned(resolved);}}));}
@EventHandler(priority=EventPriority.HIGHEST)public void click(org.bukkit.event.inventory.InventoryClickEvent event){if(event.getWhoClicked() instanceof Player actor&&sessions.downed(actor.getUniqueId()).isPresent())event.setCancelled(true);if(!(event.getView().getTopInventory().getHolder() instanceof Holder holder))return;event.setCancelled(true);if(!(event.getWhoClicked() instanceof Player player)||event.getRawSlot()!=11)return;var episode=directory.all().stream().filter(value->value.id().equals(holder.episode())&&value.player().equals(player.getUniqueId())&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);if(episode!=null)finalizeDeath(episode,"accept_death");}
@EventHandler(priority=EventPriority.HIGHEST)public void drag(org.bukkit.event.inventory.InventoryDragEvent event){if(event.getWhoClicked() instanceof Player actor&&sessions.downed(actor.getUniqueId()).isPresent()||event.getView().getTopInventory().getHolder() instanceof Holder)event.setCancelled(true);}
@EventHandler(priority=EventPriority.MONITOR)public void closeMenu(org.bukkit.event.inventory.InventoryCloseEvent event){if(!(event.getView().getTopInventory().getHolder() instanceof Holder holder)||closed)return;plugin.getServer().getScheduler().runTask(plugin,()->directory.all().stream().filter(value->value.id().equals(holder.episode())&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().ifPresent(this::open));}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void damage(org.bukkit.event.entity.EntityDamageEvent event){if(event.getEntity() instanceof Player player&&(sessions.downed(player.getUniqueId()).isPresent()||sessions.downedProtected(player.getUniqueId())))event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void damage(org.bukkit.event.entity.EntityDamageEvent event){if(!(event.getEntity() instanceof Player player))return;var episode=sessions.downed(player.getUniqueId()).orElse(null);boolean protectedRevive=episode==null&&sessions.downedProtected(player.getUniqueId());if(episode!=null||protectedRevive){event.setCancelled(true);if(events!=null){var authority=episode!=null?episode:directory.all().stream().filter(value->value.player().equals(player.getUniqueId())&&value.outcome()==DownedEpisode.Outcome.REVIVED&&value.protectionUntil()!=null&&clock.instant().isBefore(value.protectionUntil())).max(java.util.Comparator.comparing(DownedEpisode::resolvedAt)).orElse(null);if(authority!=null)events.prevented(authority,episode!=null?"downed_waiting":"revive_protection",Math.max(0,event.getFinalDamage()));}}}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void heal(org.bukkit.event.entity.EntityRegainHealthEvent event){if(event.getEntity() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void move(org.bukkit.event.player.PlayerMoveEvent event){var episode=sessions.downed(event.getPlayer().getUniqueId()).orElse(null);if(episode==null||event.getTo()==null)return;if(event.getFrom().getX()!=event.getTo().getX()||event.getFrom().getY()!=event.getTo().getY()||event.getFrom().getZ()!=event.getTo().getZ())event.setTo(event.getFrom());}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void teleport(org.bukkit.event.player.PlayerTeleportEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent()&&!sessions.downedRelocation(event.getPlayer().getUniqueId()))event.setCancelled(true);}
@@ -53,5 +56,5 @@ public final class DownedController implements Listener,AutoCloseable{
@EventHandler(priority=EventPriority.MONITOR)public void slot(io.papermc.paper.event.player.PlayerInventorySlotChangeEvent event){var player=event.getPlayer();if(sessions.downed(player.getUniqueId()).isEmpty()||!revertingSlots.add(player.getUniqueId()))return;var old=event.getOldItemStack()==null?null:event.getOldItemStack().clone();schedule(()->{try{if(sessions.downed(player.getUniqueId()).isPresent())player.getInventory().setItem(event.getSlot(),old);}finally{revertingSlots.remove(player.getUniqueId());}});}
@EventHandler(priority=EventPriority.MONITOR)public void quit(org.bukkit.event.player.PlayerQuitEvent event){release(event.getPlayer());}
private void schedule(Runnable action){try{plugin.getServer().getScheduler().runTask(plugin,action);}catch(RuntimeException failure){report(failure);}}private void report(Throwable failure){try{failures.accept(failure);}catch(RuntimeException ignored){}}
@Override public void close(){closed=true;if(pulse!=null)pulse.cancel();pulse=null;for(UUID player:java.util.List.copyOf(gravity.keySet())){var online=plugin.getServer().getPlayer(player);if(online!=null)release(online);}gravity.clear();revertingSlots.clear();}
@Override public void close(){closed=true;if(pulse!=null)pulse.cancel();pulse=null;for(UUID player:java.util.List.copyOf(gravity.keySet())){var online=plugin.getServer().getPlayer(player);if(online!=null)release(online);}gravity.clear();revertingSlots.clear();endedProtection.clear();}
}
@@ -22,16 +22,26 @@ public final class DownedDirectory implements AutoCloseable{
public DownedDirectory(Path data,Clock clock)throws IOException{file=data.toAbsolutePath().resolve("downed.yml");this.clock=Objects.requireNonNull(clock);snapshot=load();}
public CompletableFuture<Optional<DownedEpisode>> find(UUID character){return submit(()->Optional.ofNullable(snapshot.get(character)));}
public List<DownedEpisode> all(){return List.copyOf(snapshot.values());}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,Duration timeout,DownedEpisode.Attribution attribution){return begin(character,player,session,world,x,y,z,yaw,pitch,world,x,y,z,yaw,pitch,timeout,attribution);}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,Duration timeout,DownedEpisode.Attribution attribution){Objects.requireNonNull(timeout);if(timeout.isZero()||timeout.isNegative()||timeout.compareTo(Duration.ofDays(365))>0)throw new IllegalArgumentException("Invalid downed timeout");return submit(()->{var existing=snapshot.get(character);if(existing!=null&&existing.phase()==DownedEpisode.Phase.PENDING)return existing;if(snapshot.values().stream().anyMatch(value->value.player().equals(player)&&value.phase()==DownedEpisode.Phase.PENDING))throw new IOException("Player already has a downed episode");var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);var value=new DownedEpisode(UUID.randomUUID(),character,player,session,world,x,y,z,yaw,pitch,entryWorld,entryX,entryY,entryZ,entryYaw,entryPitch,now,now.plus(timeout),attribution,DownedEpisode.Phase.PENDING,null,null,null,null,List.of(),false);var next=new LinkedHashMap<>(snapshot);next.put(character,value);save(next);return value;});}
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection){return claim(episodeId,outcome,operation,protection,List.of());}
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection,List<DownedEpisode.Reward> rewards){Objects.requireNonNull(episodeId);Objects.requireNonNull(outcome);Objects.requireNonNull(operation);Objects.requireNonNull(protection);rewards=List.copyOf(rewards);if(protection.isNegative()||protection.compareTo(Duration.ofDays(365))>0||outcome==DownedEpisode.Outcome.REVIVED&&!rewards.isEmpty())throw new IllegalArgumentException("Invalid protection or rewards");var capturedRewards=rewards;return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElse(null);if(current==null)return new Claim(ClaimStatus.NOT_FOUND,Optional.empty());if(current.phase()==DownedEpisode.Phase.RESOLVED)return new Claim(ClaimStatus.ALREADY_RESOLVED,Optional.of(current));var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);if(outcome==DownedEpisode.Outcome.REVIVED&&!now.isBefore(current.expiresAt()))return new Claim(ClaimStatus.EXPIRED,Optional.of(current));var resolvedAt=outcome==DownedEpisode.Outcome.FINAL_DEATH&&!now.isBefore(current.expiresAt())?current.expiresAt():now;var protectionUntil=outcome==DownedEpisode.Outcome.REVIVED?resolvedAt.plus(protection):null;var resolved=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),DownedEpisode.Phase.RESOLVED,outcome,operation,resolvedAt,protectionUntil,capturedRewards,false);var next=new LinkedHashMap<>(snapshot);next.put(resolved.character(),resolved);save(next);return new Claim(ClaimStatus.APPLIED,Optional.of(resolved));});}
public CompletableFuture<DownedEpisode> publish(UUID episodeId,UUID operation){Objects.requireNonNull(episodeId);Objects.requireNonNull(operation);return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElseThrow(()->new IOException("Downed episode not found"));if(current.phase()!=DownedEpisode.Phase.RESOLVED||!operation.equals(current.outcomeOperation()))throw new IOException("Downed outcome operation does not match");if(current.published())return current;var published=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),current.phase(),current.outcome(),current.outcomeOperation(),current.resolvedAt(),current.protectionUntil(),current.finalRewards(),true);var next=new LinkedHashMap<>(snapshot);next.put(published.character(),published);save(next);return published;});}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,Duration timeout,DownedEpisode.Attribution attribution){return begin(character,player,session,world,x,y,z,yaw,pitch,world,x,y,z,yaw,pitch,null,null,null,timeout,attribution);}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,Duration timeout,DownedEpisode.Attribution attribution){return begin(character,player,session,world,x,y,z,yaw,pitch,entryWorld,entryX,entryY,entryZ,entryYaw,entryPitch,null,null,null,timeout,attribution);}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,java.math.BigInteger characterRevision,Duration timeout,DownedEpisode.Attribution attribution){return begin(character,player,session,world,x,y,z,yaw,pitch,entryWorld,entryX,entryY,entryZ,entryYaw,entryPitch,null,null,characterRevision,timeout,attribution);}
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,String characterName,String playerName,java.math.BigInteger characterRevision,Duration timeout,DownedEpisode.Attribution attribution){Objects.requireNonNull(timeout);if(timeout.isZero()||timeout.isNegative()||timeout.compareTo(Duration.ofDays(365))>0)throw new IllegalArgumentException("Invalid downed timeout");return submit(()->{var existing=snapshot.get(character);if(existing!=null&&existing.phase()==DownedEpisode.Phase.PENDING)return existing;if(snapshot.values().stream().anyMatch(value->value.player().equals(player)&&value.phase()==DownedEpisode.Phase.PENDING))throw new IOException("Player already has a downed episode");var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);var value=new DownedEpisode(UUID.randomUUID(),character,player,session,world,x,y,z,yaw,pitch,entryWorld,entryX,entryY,entryZ,entryYaw,entryPitch,now,now.plus(timeout),attribution,characterName,playerName,characterRevision,DownedEpisode.Phase.PENDING,null,null,null,null,null,List.of(),false);var next=new LinkedHashMap<>(snapshot);next.put(character,value);save(next);return value;});}
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection){return claim(episodeId,outcome,operation,null,protection,List.of());}
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection,List<DownedEpisode.Reward> rewards){return claim(episodeId,outcome,operation,null,protection,rewards);}
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,DownedEpisode.Decision decision,Duration protection,List<DownedEpisode.Reward> rewards){Objects.requireNonNull(episodeId);Objects.requireNonNull(outcome);Objects.requireNonNull(operation);Objects.requireNonNull(protection);if(decision!=null&&!operation.equals(decision.actionId()))throw new IllegalArgumentException("Decision action does not match outcome operation");rewards=List.copyOf(rewards);if(protection.isNegative()||protection.compareTo(Duration.ofDays(365))>0||outcome==DownedEpisode.Outcome.REVIVED&&!rewards.isEmpty())throw new IllegalArgumentException("Invalid protection or rewards");var capturedRewards=rewards;return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElse(null);if(current==null)return new Claim(ClaimStatus.NOT_FOUND,Optional.empty());if(current.phase()==DownedEpisode.Phase.RESOLVED)return new Claim(ClaimStatus.ALREADY_RESOLVED,Optional.of(current));var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);if(outcome==DownedEpisode.Outcome.REVIVED&&!now.isBefore(current.expiresAt()))return new Claim(ClaimStatus.EXPIRED,Optional.of(current));var resolvedAt=outcome==DownedEpisode.Outcome.FINAL_DEATH&&!now.isBefore(current.expiresAt())?current.expiresAt():now;var protectionUntil=outcome==DownedEpisode.Outcome.REVIVED?resolvedAt.plus(protection):null;var resolved=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),current.characterName(),current.playerName(),current.characterRevision(),DownedEpisode.Phase.RESOLVED,outcome,operation,resolvedAt,protectionUntil,decision,capturedRewards,false);var next=new LinkedHashMap<>(snapshot);next.put(resolved.character(),resolved);save(next);return new Claim(ClaimStatus.APPLIED,Optional.of(resolved));});}
public CompletableFuture<DownedEpisode> publish(UUID episodeId,UUID operation){Objects.requireNonNull(episodeId);Objects.requireNonNull(operation);return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElseThrow(()->new IOException("Downed episode not found"));if(current.phase()!=DownedEpisode.Phase.RESOLVED||!operation.equals(current.outcomeOperation()))throw new IOException("Downed outcome operation does not match");if(current.published())return current;var published=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),current.characterName(),current.playerName(),current.characterRevision(),current.phase(),current.outcome(),current.outcomeOperation(),current.resolvedAt(),current.protectionUntil(),current.decision(),current.finalRewards(),true);var next=new LinkedHashMap<>(snapshot);next.put(published.character(),published);save(next);return published;});}
private Map<UUID,DownedEpisode> load()throws IOException{if(Files.notExists(file))return Map.of();try{if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS)||Files.isSymbolicLink(file)||Files.size(file)>1_048_576)throw new IllegalArgumentException();Object decoded=yaml().load(Files.readString(file,StandardCharsets.UTF_8));if(!(decoded instanceof Map<?,?> root)||!"1".equals(String.valueOf(root.get("schema-version"))))throw new IllegalArgumentException();var result=new LinkedHashMap<UUID,DownedEpisode>();for(Object raw:list(root.get("episodes"))){var row=map(raw);var value=decode(row);if(result.put(value.character(),value)!=null)throw new IllegalArgumentException();}return Map.copyOf(result);}catch(RuntimeException invalid){throw new IOException("Invalid downed state",invalid);}}
private void save(Map<UUID,DownedEpisode> state)throws IOException{Files.createDirectories(file.getParent());var root=new LinkedHashMap<String,Object>();root.put("schema-version","1");root.put("episodes",state.values().stream().sorted(Comparator.comparing(DownedEpisode::character)).map(this::encode).toList());Path temporary=Files.createTempFile(file.getParent(),".downed-",".tmp");try{byte[] bytes=yaml().dump(root).getBytes(StandardCharsets.UTF_8);try(var out=FileChannel.open(temporary,StandardOpenOption.WRITE)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())out.write(buffer);out.force(true);}Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);try(var directory=FileChannel.open(file.getParent(),StandardOpenOption.READ)){directory.force(true);}snapshot=Map.copyOf(state);}finally{Files.deleteIfExists(temporary);}}
private Map<String,Object> encode(DownedEpisode value){var row=new LinkedHashMap<String,Object>();row.put("id",value.id().toString());row.put("character",value.character().toString());row.put("player",value.player().toString());row.put("session",value.session().toString());row.put("world",value.world().toString());row.put("x",BigDecimal.valueOf(value.x()).toPlainString());row.put("y",BigDecimal.valueOf(value.y()).toPlainString());row.put("z",BigDecimal.valueOf(value.z()).toPlainString());row.put("yaw",Float.toString(value.yaw()));row.put("pitch",Float.toString(value.pitch()));row.put("entry-world",value.entryWorld().toString());row.put("entry-x",BigDecimal.valueOf(value.entryX()).toPlainString());row.put("entry-y",BigDecimal.valueOf(value.entryY()).toPlainString());row.put("entry-z",BigDecimal.valueOf(value.entryZ()).toPlainString());row.put("entry-yaw",Float.toString(value.entryYaw()));row.put("entry-pitch",Float.toString(value.entryPitch()));row.put("downed-at",value.downedAt().toString());row.put("expires-at",value.expiresAt().toString());row.put("attacker",value.attribution().attacker()==null?null:value.attribution().attacker().toString());row.put("cause",value.attribution().cause());row.put("player-defeat",value.attribution().playerDefeat());row.put("contributors",value.attribution().contributors().stream().map(UUID::toString).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("victim-level",value.attribution().victimLevel());row.put("victim-coins",value.attribution().victimCoins().toString());row.put("phase",value.phase().name());row.put("outcome",value.outcome()==null?null:value.outcome().name());row.put("outcome-operation",value.outcomeOperation()==null?null:value.outcomeOperation().toString());row.put("resolved-at",value.resolvedAt()==null?null:value.resolvedAt().toString());row.put("protection-until",value.protectionUntil()==null?null:value.protectionUntil().toString());row.put("final-rewards",value.finalRewards().stream().map(reward->{var saved=new LinkedHashMap<String,Object>();saved.put("character",reward.character().toString());saved.put("experience",reward.experience().toString());saved.put("coins",reward.coins().toString());return saved;}).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("published",value.published());return row;}
private DownedEpisode decode(Map<?,?> row){String attacker=optional(row,"attacker"),outcome=optional(row,"outcome"),operation=optional(row,"outcome-operation"),resolved=optional(row,"resolved-at"),protection=optional(row,"protection-until");UUID world=uuid(row,"world"),entryWorld=row.containsKey("entry-world")?uuid(row,"entry-world"):world;double x=Double.parseDouble(text(row,"x")),y=Double.parseDouble(text(row,"y")),z=Double.parseDouble(text(row,"z"));float yaw=Float.parseFloat(text(row,"yaw")),pitch=Float.parseFloat(text(row,"pitch"));return new DownedEpisode(uuid(row,"id"),uuid(row,"character"),uuid(row,"player"),uuid(row,"session"),world,x,y,z,yaw,pitch,entryWorld,row.containsKey("entry-x")?Double.parseDouble(text(row,"entry-x")):x,row.containsKey("entry-y")?Double.parseDouble(text(row,"entry-y")):y,row.containsKey("entry-z")?Double.parseDouble(text(row,"entry-z")):z,row.containsKey("entry-yaw")?Float.parseFloat(text(row,"entry-yaw")):yaw,row.containsKey("entry-pitch")?Float.parseFloat(text(row,"entry-pitch")):pitch,Instant.parse(text(row,"downed-at")),Instant.parse(text(row,"expires-at")),new DownedEpisode.Attribution(attacker==null?null:UUID.fromString(attacker),text(row,"cause"),Boolean.parseBoolean(String.valueOf(row.containsKey("player-defeat")?row.get("player-defeat"):false)),row.containsKey("contributors")?list(row.get("contributors")).stream().map(String::valueOf).map(UUID::fromString).toList():List.of(),row.containsKey("victim-level")?Integer.parseInt(String.valueOf(row.get("victim-level"))):0,row.containsKey("victim-coins")?new java.math.BigInteger(String.valueOf(row.get("victim-coins"))):java.math.BigInteger.ZERO),DownedEpisode.Phase.valueOf(text(row,"phase")),outcome==null?null:DownedEpisode.Outcome.valueOf(outcome),operation==null?null:UUID.fromString(operation),resolved==null?null:Instant.parse(resolved),protection==null?null:Instant.parse(protection),list(row.get("final-rewards")).stream().map(DownedDirectory::map).map(reward->new DownedEpisode.Reward(uuid(reward,"character"),new java.math.BigInteger(text(reward,"experience")),new java.math.BigInteger(text(reward,"coins")))).toList(),Boolean.parseBoolean(String.valueOf(row.containsKey("published")?row.get("published"):false)));}
private Map<String,Object> encode(DownedEpisode value){var row=new LinkedHashMap<String,Object>();row.put("id",value.id().toString());row.put("character",value.character().toString());row.put("player",value.player().toString());row.put("session",value.session().toString());row.put("world",value.world().toString());row.put("x",BigDecimal.valueOf(value.x()).toPlainString());row.put("y",BigDecimal.valueOf(value.y()).toPlainString());row.put("z",BigDecimal.valueOf(value.z()).toPlainString());row.put("yaw",Float.toString(value.yaw()));row.put("pitch",Float.toString(value.pitch()));row.put("entry-world",value.entryWorld().toString());row.put("entry-x",BigDecimal.valueOf(value.entryX()).toPlainString());row.put("entry-y",BigDecimal.valueOf(value.entryY()).toPlainString());row.put("entry-z",BigDecimal.valueOf(value.entryZ()).toPlainString());row.put("entry-yaw",Float.toString(value.entryYaw()));row.put("entry-pitch",Float.toString(value.entryPitch()));row.put("downed-at",value.downedAt().toString());row.put("expires-at",value.expiresAt().toString());row.put("attacker",value.attribution().attacker()==null?null:value.attribution().attacker().toString());row.put("cause",value.attribution().cause());row.put("player-defeat",value.attribution().playerDefeat());row.put("contributors",value.attribution().contributors().stream().map(UUID::toString).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("victim-level",value.attribution().victimLevel());row.put("victim-coins",value.attribution().victimCoins().toString());row.put("character-name",value.characterName());row.put("player-name",value.playerName());row.put("character-revision",value.characterRevision()==null?null:value.characterRevision().toString());row.put("phase",value.phase().name());row.put("outcome",value.outcome()==null?null:value.outcome().name());row.put("outcome-operation",value.outcomeOperation()==null?null:value.outcomeOperation().toString());row.put("resolved-at",value.resolvedAt()==null?null:value.resolvedAt().toString());row.put("protection-until",value.protectionUntil()==null?null:value.protectionUntil().toString());var decision=value.decision();row.put("decision-source",decision==null?null:decision.source());row.put("decision-actor-player",decision==null||decision.actorPlayer()==null?null:decision.actorPlayer().toString());row.put("decision-actor-player-name",decision==null?null:decision.actorPlayerName());row.put("decision-actor-character",decision==null||decision.actorCharacter()==null?null:decision.actorCharacter().toString());row.put("decision-actor-character-name",decision==null?null:decision.actorCharacterName());row.put("decision-actor-session",decision==null||decision.actorSession()==null?null:decision.actorSession().toString());row.put("decision-action",decision==null?null:decision.actionId().toString());row.put("decision-cast-at",decision==null||decision.castAt()==null?null:decision.castAt().toString());row.put("decision-cooldown-until",decision==null||decision.cooldownUntil()==null?null:decision.cooldownUntil().toString());row.put("decision-final-range",decision==null||decision.finalRange()==null?null:Double.toString(decision.finalRange()));row.put("decision-line-of-sight",decision==null?null:decision.lineOfSight());row.put("final-rewards",value.finalRewards().stream().map(reward->{var saved=new LinkedHashMap<String,Object>();saved.put("character",reward.character().toString());saved.put("experience",reward.experience().toString());saved.put("coins",reward.coins().toString());return saved;}).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("published",value.published());return row;}
private DownedEpisode decode(Map<?,?> row){
String attacker=optional(row,"attacker"),outcome=optional(row,"outcome"),operation=optional(row,"outcome-operation"),resolved=optional(row,"resolved-at"),protection=optional(row,"protection-until"),revision=optional(row,"character-revision"),characterName=optional(row,"character-name"),playerName=optional(row,"player-name"),decisionSource=optional(row,"decision-source"),decisionPlayer=optional(row,"decision-actor-player"),decisionPlayerName=optional(row,"decision-actor-player-name"),decisionCharacter=optional(row,"decision-actor-character"),decisionCharacterName=optional(row,"decision-actor-character-name"),decisionSession=optional(row,"decision-actor-session"),decisionAction=optional(row,"decision-action"),decisionCastAt=optional(row,"decision-cast-at"),decisionCooldown=optional(row,"decision-cooldown-until"),decisionRange=optional(row,"decision-final-range");
UUID world=uuid(row,"world"),entryWorld=row.containsKey("entry-world")?uuid(row,"entry-world"):world;
double x=Double.parseDouble(text(row,"x")),y=Double.parseDouble(text(row,"y")),z=Double.parseDouble(text(row,"z"));
float yaw=Float.parseFloat(text(row,"yaw")),pitch=Float.parseFloat(text(row,"pitch"));
var decision=decisionSource==null?null:new DownedEpisode.Decision(decisionSource,decisionPlayer==null?null:UUID.fromString(decisionPlayer),decisionPlayerName,decisionCharacter==null?null:UUID.fromString(decisionCharacter),decisionCharacterName,decisionSession==null?null:UUID.fromString(decisionSession),UUID.fromString(decisionAction),decisionCastAt==null?null:Instant.parse(decisionCastAt),decisionCooldown==null?null:Instant.parse(decisionCooldown),decisionRange==null?null:Double.valueOf(decisionRange),row.get("decision-line-of-sight")==null?null:Boolean.valueOf(String.valueOf(row.get("decision-line-of-sight"))));
return new DownedEpisode(uuid(row,"id"),uuid(row,"character"),uuid(row,"player"),uuid(row,"session"),world,x,y,z,yaw,pitch,entryWorld,row.containsKey("entry-x")?Double.parseDouble(text(row,"entry-x")):x,row.containsKey("entry-y")?Double.parseDouble(text(row,"entry-y")):y,row.containsKey("entry-z")?Double.parseDouble(text(row,"entry-z")):z,row.containsKey("entry-yaw")?Float.parseFloat(text(row,"entry-yaw")):yaw,row.containsKey("entry-pitch")?Float.parseFloat(text(row,"entry-pitch")):pitch,Instant.parse(text(row,"downed-at")),Instant.parse(text(row,"expires-at")),new DownedEpisode.Attribution(attacker==null?null:UUID.fromString(attacker),text(row,"cause"),Boolean.parseBoolean(String.valueOf(row.containsKey("player-defeat")?row.get("player-defeat"):false)),row.containsKey("contributors")?list(row.get("contributors")).stream().map(String::valueOf).map(UUID::fromString).toList():List.of(),row.containsKey("victim-level")?Integer.parseInt(String.valueOf(row.get("victim-level"))):0,row.containsKey("victim-coins")?new java.math.BigInteger(String.valueOf(row.get("victim-coins"))):java.math.BigInteger.ZERO),characterName,playerName,revision==null?null:new java.math.BigInteger(revision),DownedEpisode.Phase.valueOf(text(row,"phase")),outcome==null?null:DownedEpisode.Outcome.valueOf(outcome),operation==null?null:UUID.fromString(operation),resolved==null?null:Instant.parse(resolved),protection==null?null:Instant.parse(protection),decision,list(row.get("final-rewards")).stream().map(DownedDirectory::map).map(reward->new DownedEpisode.Reward(uuid(reward,"character"),new java.math.BigInteger(text(reward,"experience")),new java.math.BigInteger(text(reward,"coins")))).toList(),Boolean.parseBoolean(String.valueOf(row.containsKey("published")?row.get("published"):false)));
}
private static Yaml yaml(){var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(0);options.setCodePointLimit(1_048_576);return new Yaml(new SafeConstructor(options));}private static List<?> list(Object value){return value==null?List.of():(List<?>)value;}private static Map<?,?> map(Object value){return(Map<?,?>)value;}private static String text(Map<?,?> map,String key){Object value=map.get(key);if(!(value instanceof String text)||text.isBlank())throw new IllegalArgumentException(key);return text;}private static String optional(Map<?,?> map,String key){Object value=map.get(key);return value==null?null:text(map,key);}private static UUID uuid(Map<?,?> map,String key){return UUID.fromString(text(map,key));}
private <T>CompletableFuture<T> submit(Callable<T> work){var result=new CompletableFuture<T>();synchronized(this){if(closed){result.completeExceptionally(new IOException("Downed directory closed"));return result;}pending++;}worker.execute(()->{try{result.complete(work.call());}catch(Throwable failure){result.completeExceptionally(failure);}finally{finished();}});return result;}private synchronized void finished(){pending--;if(closed&&pending==0)drained.complete(null);}public CompletionStage<Void> drained(){return drained.minimalCompletionStage();}@Override public synchronized void close(){closed=true;worker.shutdown();if(pending==0)drained.complete(null);}
}
@@ -7,19 +7,120 @@ import java.util.Objects;
import java.util.UUID;
/** Durable identity, anchor, attribution and single resolution for one lethal episode. */
public record DownedEpisode(UUID id,UUID character,UUID player,UUID session,UUID world,
double x,double y,double z,float yaw,float pitch,
UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,
Instant downedAt,Instant expiresAt,Attribution attribution,
Phase phase,Outcome outcome,UUID outcomeOperation,
Instant resolvedAt,Instant protectionUntil,List<Reward> finalRewards,boolean published){
public enum Phase{PENDING,RESOLVED}
public enum Outcome{REVIVED,FINAL_DEATH}
public record Reward(UUID character,BigInteger experience,BigInteger coins){public Reward{Objects.requireNonNull(character);Objects.requireNonNull(experience);Objects.requireNonNull(coins);if(experience.signum()<0||coins.signum()<0)throw new IllegalArgumentException("Invalid downed reward");}}
public record Attribution(UUID attacker,String cause,boolean playerDefeat,List<UUID> contributors,int victimLevel,BigInteger victimCoins){
public Attribution(UUID attacker,String cause){this(attacker,cause,false,List.of(),0,BigInteger.ZERO);}
public Attribution(UUID attacker,String cause,boolean playerDefeat){this(attacker,cause,playerDefeat,List.of(),0,BigInteger.ZERO);}
public Attribution{if(cause==null||cause.isBlank()||victimLevel<0||victimCoins==null||victimCoins.signum()<0)throw new IllegalArgumentException("Invalid lethal attribution");contributors=List.copyOf(contributors);}
public record DownedEpisode(UUID id, UUID character, UUID player, UUID session, UUID world,
double x, double y, double z, float yaw, float pitch,
UUID entryWorld, double entryX, double entryY, double entryZ,
float entryYaw, float entryPitch, Instant downedAt, Instant expiresAt,
Attribution attribution, String characterName, String playerName,
BigInteger characterRevision, Phase phase,
Outcome outcome, UUID outcomeOperation, Instant resolvedAt,
Instant protectionUntil, Decision decision, List<Reward> finalRewards,
boolean published) {
public enum Phase { PENDING, RESOLVED }
public enum Outcome { REVIVED, FINAL_DEATH }
public record Reward(UUID character, BigInteger experience, BigInteger coins) {
public Reward {
Objects.requireNonNull(character);
Objects.requireNonNull(experience);
Objects.requireNonNull(coins);
if (experience.signum() < 0 || coins.signum() < 0) {
throw new IllegalArgumentException("Invalid downed reward");
}
}
}
public record Attribution(UUID attacker, String cause, boolean playerDefeat,
List<UUID> contributors, int victimLevel, BigInteger victimCoins) {
public Attribution(UUID attacker, String cause) {
this(attacker, cause, false, List.of(), 0, BigInteger.ZERO);
}
public Attribution(UUID attacker, String cause, boolean playerDefeat) {
this(attacker, cause, playerDefeat, List.of(), 0, BigInteger.ZERO);
}
public Attribution {
if (cause == null || cause.isBlank() || victimLevel < 0 || victimCoins == null
|| victimCoins.signum() < 0) throw new IllegalArgumentException("Invalid lethal attribution");
contributors = List.copyOf(contributors);
}
}
/** Durable winning decision context; nullable actor fields represent an automatic system timeout. */
public record Decision(String source, UUID actorPlayer, String actorPlayerName,
UUID actorCharacter, String actorCharacterName, UUID actorSession,
UUID actionId, Instant castAt, Instant cooldownUntil,
Double finalRange, Boolean lineOfSight) {
public Decision {
if (source == null || !List.of("revive", "accept_death", "timeout").contains(source)
|| actionId == null || (actorPlayer == null) != (actorPlayerName == null)
|| (actorCharacter == null) != (actorCharacterName == null)
|| (actorCharacter == null) != (actorSession == null)
|| finalRange != null && (!Double.isFinite(finalRange) || finalRange < 0)
|| "revive".equals(source) && (actorPlayer == null || actorCharacter == null
|| castAt == null || cooldownUntil == null || finalRange == null || lineOfSight == null)) {
throw new IllegalArgumentException("Invalid downed decision");
}
}
}
/** Backward-compatible construction for callers and legacy records created before event context existed. */
public DownedEpisode(UUID id, UUID character, UUID player, UUID session, UUID world,
double x, double y, double z, float yaw, float pitch,
UUID entryWorld, double entryX, double entryY, double entryZ,
float entryYaw, float entryPitch, Instant downedAt, Instant expiresAt,
Attribution attribution, Phase phase, Outcome outcome, UUID outcomeOperation,
Instant resolvedAt, Instant protectionUntil, List<Reward> finalRewards,
boolean published) {
this(id, character, player, session, world, x, y, z, yaw, pitch, entryWorld, entryX, entryY,
entryZ, entryYaw, entryPitch, downedAt, expiresAt, attribution, null, null, null, phase, outcome,
outcomeOperation, resolvedAt, protectionUntil,
legacyDecision(expiresAt, outcome, outcomeOperation, resolvedAt), finalRewards, published);
}
private static Decision legacyDecision(Instant expiresAt, Outcome outcome, UUID operation,
Instant resolvedAt) {
if (outcome == null || operation == null || resolvedAt == null) return null;
String source = outcome == Outcome.REVIVED ? "revive"
: resolvedAt.equals(expiresAt) ? "timeout" : "accept_death";
// Legacy Revive lacks durable caster/cooldown/range evidence, so do not fabricate a decision actor.
if (outcome == Outcome.REVIVED) return null;
return new Decision(source, null, null, null, null, null, operation, null, null, null, null);
}
public DownedEpisode {
Objects.requireNonNull(id);
Objects.requireNonNull(character);
Objects.requireNonNull(player);
Objects.requireNonNull(session);
Objects.requireNonNull(world);
Objects.requireNonNull(entryWorld);
Objects.requireNonNull(downedAt);
Objects.requireNonNull(expiresAt);
Objects.requireNonNull(attribution);
if ((characterName == null) != (playerName == null)) {
throw new IllegalArgumentException("Incomplete downed subject names");
}
Objects.requireNonNull(phase);
finalRewards = List.copyOf(finalRewards);
if (characterRevision != null && characterRevision.signum() < 0
|| !Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)
|| !Float.isFinite(yaw) || !Float.isFinite(pitch)
|| !Double.isFinite(entryX) || !Double.isFinite(entryY) || !Double.isFinite(entryZ)
|| !Float.isFinite(entryYaw) || !Float.isFinite(entryPitch)
|| !expiresAt.isAfter(downedAt)) throw new IllegalArgumentException("Invalid downed episode");
boolean resolved = phase == Phase.RESOLVED;
if (resolved != (outcome != null && outcomeOperation != null && resolvedAt != null)) {
throw new IllegalArgumentException("Invalid downed outcome");
}
if (decision != null && (!resolved || !decision.actionId().equals(outcomeOperation))) {
throw new IllegalArgumentException("Invalid downed decision identity");
}
if (!resolved && protectionUntil != null || outcome == Outcome.FINAL_DEATH && protectionUntil != null
|| protectionUntil != null && protectionUntil.isBefore(resolvedAt)) {
throw new IllegalArgumentException("Invalid downed protection");
}
if ((!resolved || outcome == Outcome.REVIVED) && !finalRewards.isEmpty()) {
throw new IllegalArgumentException("Invalid downed rewards");
}
}
public DownedEpisode{Objects.requireNonNull(id);Objects.requireNonNull(character);Objects.requireNonNull(player);Objects.requireNonNull(session);Objects.requireNonNull(world);Objects.requireNonNull(entryWorld);Objects.requireNonNull(downedAt);Objects.requireNonNull(expiresAt);Objects.requireNonNull(attribution);Objects.requireNonNull(phase);finalRewards=List.copyOf(finalRewards);if(!Double.isFinite(x)||!Double.isFinite(y)||!Double.isFinite(z)||!Float.isFinite(yaw)||!Float.isFinite(pitch)||!Double.isFinite(entryX)||!Double.isFinite(entryY)||!Double.isFinite(entryZ)||!Float.isFinite(entryYaw)||!Float.isFinite(entryPitch)||!expiresAt.isAfter(downedAt))throw new IllegalArgumentException("Invalid downed episode");boolean resolved=phase==Phase.RESOLVED;if(resolved!=(outcome!=null&&outcomeOperation!=null&&resolvedAt!=null))throw new IllegalArgumentException("Invalid downed outcome");if(!resolved&&protectionUntil!=null||outcome==Outcome.FINAL_DEATH&&protectionUntil!=null||protectionUntil!=null&&protectionUntil.isBefore(resolvedAt))throw new IllegalArgumentException("Invalid downed protection");if((!resolved||outcome==Outcome.REVIVED)&&!finalRewards.isEmpty())throw new IllegalArgumentException("Invalid downed rewards");}
}
@@ -101,6 +101,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
private games.dmg.fantasystick.shop.RareMarket rareMarket;
private games.dmg.fantasystick.persistence.RareSettings rareSettings;
private games.dmg.fantasystick.persistence.DownedSettings downedSettings;
private games.dmg.fantasystick.events.DownedEventBridge downedEvents;
private games.dmg.fantasystick.book.CharacterBookController characterBooks;
private games.dmg.fantasystick.persistence.CharacterStorage characters;
private AdminCharacterRecovery characterRecovery;
@@ -425,6 +426,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
public void attachArmorMarket(games.dmg.fantasystick.shop.ArmorMarket market){if(closed||armorMarket!=null)throw new IllegalStateException("Armor market already attached or command closed");armorMarket=Objects.requireNonNull(market);}
public void attachRareMarket(games.dmg.fantasystick.shop.RareMerchantDirectory directory,games.dmg.fantasystick.shop.RareMerchantController controller,games.dmg.fantasystick.shop.RareMarket market,games.dmg.fantasystick.persistence.RareSettings settings){if(closed||rareMerchants!=null)throw new IllegalStateException("Rare market already attached or command closed");rareMerchants=Objects.requireNonNull(directory);rareMerchantController=Objects.requireNonNull(controller);rareMarket=Objects.requireNonNull(market);rareSettings=Objects.requireNonNull(settings);}
public void attachDownedSettings(games.dmg.fantasystick.persistence.DownedSettings settings){if(closed||downedSettings!=null)throw new IllegalStateException("Downed settings already attached or command closed");downedSettings=Objects.requireNonNull(settings);}
public void attachDownedEvents(games.dmg.fantasystick.events.DownedEventBridge events){if(closed||downedEvents!=null)throw new IllegalStateException("Downed events already attached or command closed");downedEvents=Objects.requireNonNull(events);}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (closed) return true;
@@ -1557,7 +1559,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
private void gearConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+gearSettings.value(key)+" (applies to the next armor restock only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.GearSettings.Update> operation;try{operation=gearSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Armor market setting is invalid; variance is 0–100, prices are nonnegative, and positive stock minima cannot exceed maxima.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&gearSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Armor market setting save failed; effective settings and the current catalog are unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+gearSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+" for the next automatic or administrative restock; the current catalog is unchanged.");});});}
private void rareConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+rareSettings.value(key)+(key.endsWith("-healing-percent")?" (applies to future accepted uses)":" (applies to the next rare restock only)"));return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.RareSettings.Update> operation;try{operation=rareSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Rare setting is invalid; percentages are 0–100, values are nonnegative, and stock minima cannot exceed maxima.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&rareSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Rare setting save failed; prior effective state is unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+rareSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+"; current catalog and accepted uses are unchanged.");});});}
private void downedConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+downedSettings.value(key)+" (applies to future downed outcomes only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.DownedSettings.Update> operation;try{operation=downedSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Downed setting is invalid; timeout must be positive and protection may be zero, both at most 365 days.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&downedSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Downed setting save failed; prior effective state is unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+downedSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+"; existing deadlines are unchanged.");});});}
private void downedConfiguration(CommandSender sender,String[] args){String key=args[1],before=downedSettings.value(key),actorKind=sender instanceof org.bukkit.entity.Player?"player":sender instanceof org.bukkit.command.BlockCommandSender?"command_block":"console";UUID actorPlayer=sender instanceof org.bukkit.entity.Player player?player.getUniqueId():null;String actorName=sender instanceof org.bukkit.entity.Player?sender.getName():null;if(args.length==2){if(downedEvents!=null)downedEvents.configRead(actorKind,actorPlayer,actorName,key,before);sender.sendMessage(key+"="+before+" (applies to future downed outcomes only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.DownedSettings.Update> operation;try{operation=downedSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Downed setting is invalid; timeout must be positive and protection may be zero, both at most 365 days.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&downedSettings.publish(saved);if(applied&&downedEvents!=null)downedEvents.configChanged(actorKind,actorPlayer,actorName,key,before,saved.value());if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Downed setting save failed; prior effective state is unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+downedSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+"; existing deadlines are unchanged.");});});}
private void coinConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+coinSettings.value(key)+" (applies to future creation or defeats only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.CoinSettings.Update> operation;try{operation=coinSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Coin setting is invalid; ranges must be ordered whole numbers from 0 through 2147483647.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;boolean applied=failure==null&&coinSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Coin configuration save failed; effective ranges are unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+coinSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+" for future creation or defeats; existing balances and captured rewards are unchanged.");});}catch(RuntimeException rejected){report(null,"config-response",rejected);}});}
@@ -46,6 +46,7 @@ public final class EquipmentSessions implements AutoCloseable {
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 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 =
@@ -204,6 +205,7 @@ public final class EquipmentSessions implements AutoCloseable {
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 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)));}
@@ -698,7 +700,7 @@ public final class EquipmentSessions implements AutoCloseable {
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;downedDirectory.publish(recovered.id(),recovered.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(attempt,publishFailure);});}
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();
} catch (RuntimeException error) {
@@ -760,9 +762,9 @@ public final class EquipmentSessions implements AutoCloseable {
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(),downedTimeout.get(),attribution);
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;notice(owner,"DOWNED","§cYou are downed. Accept death or wait for Revive.");try{downedPresentation.accept(episode);}catch(RuntimeException presentationFailure){diagnostic(pendingAttempt,presentationFailure);}}}));return;
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) {
@@ -847,13 +849,14 @@ public final class EquipmentSessions implements AutoCloseable {
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;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(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{if(!attempt.player.teleport(attempt.entryLocation.clone()))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;}
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;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{if(!attempt.player.teleport(attempt.entryLocation.clone()))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->dead.isEmpty()?CompletableFuture.completedStage(dead):finalConsequences(episode).thenApply(ignored->dead));}
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);});}
private void reconcileOfflineFinalDeath(Player player,DownedEpisode episode){persist(()->recordOfflineFinalDeath(episode),(dead,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null){diagnostic(new Failure(episode.player(),episode.session(),failure));return;}if(dead.isEmpty()||closed||!player.isOnline())return;var record=dead.orElseThrow();var current=player.getInventory().getItemInOffHand();var existing=tails.identify(current).orElse(null);if(existing!=null&&existing.characterId().equals(record.id())&&existing.deathId().equals(record.deathId())){downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(new Failure(episode.player(),episode.session(),publishFailure));});return;}if(!sheets.authorizes(current,record)){notice(player.getUniqueId(),"DOWNED_RECOVERY_REQUIRED","Expired downed custody does not match the exact saved sheet; no native item was changed.");return;}try{player.getInventory().setItemInOffHand(tails.create(record));player.updateInventory();downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(new Failure(episode.player(),episode.session(),publishFailure));});}catch(RuntimeException nativeFailure){diagnostic(new Failure(episode.player(),episode.session(),nativeFailure));notice(player.getUniqueId(),"DOWNED_RECOVERY_UNCERTAIN","Final-death Tail delivery was uncertain; retain inventory for inspection.");}}}));}
private void reconcileOfflineFinalDeath(Player player,DownedEpisode episode){persist(()->recordOfflineFinalDeath(episode),(dead,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null){diagnostic(new Failure(episode.player(),episode.session(),failure));return;}if(dead.isEmpty()||closed||!player.isOnline())return;var record=dead.orElseThrow();var current=player.getInventory().getItemInOffHand();var existing=tails.identify(current).orElse(null);if(existing!=null&&existing.characterId().equals(record.id())&&existing.deathId().equals(record.deathId())){publishRecoveredDowned(episode);return;}if(!sheets.authorizes(current,record)){notice(player.getUniqueId(),"DOWNED_RECOVERY_REQUIRED","Expired downed custody does not match the exact saved sheet; no native item was changed.");return;}try{player.getInventory().setItemInOffHand(tails.create(record));player.updateInventory();publishRecoveredDowned(episode);}catch(RuntimeException nativeFailure){diagnostic(new Failure(episode.player(),episode.session(),nativeFailure));notice(player.getUniqueId(),"DOWNED_RECOVERY_UNCERTAIN","Final-death Tail delivery was uncertain; retain inventory for inspection.");}}}));}
private void publishRecoveredDowned(DownedEpisode episode){if(downedEvents!=null)downedEvents.outcomePublished(episode);downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((published,failure)->{if(failure!=null)diagnostic(new Failure(episode.player(),episode.session(),failure));else if(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) {
@@ -945,7 +948,7 @@ public final class EquipmentSessions implements AutoCloseable {
}
}
private void publishDowned(DownedEpisode episode,Attempt attempt){if(episode==null||episode.published()||downedDirectory==null)return;downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,failure)->{if(failure!=null)diagnostic(attempt,failure);});}
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();