Compare commits

...
3 Commits
Author SHA1 Message Date
dmg 689877403f test(events): await downed presentation callback
Release / release (push) Successful in 13m24s
2026-09-24 20:38:55 -04:00
dmg 936e221c81 test(events): await acknowledged downed emission
Release / release (push) Failing after 7m9s
2026-09-24 09:04:20 -04:00
dmg 819a966160 feat(events): record downed combat outcomes
Release / release (push) Failing after 6m54s
2026-09-24 08:51:44 -04:00
14 changed files with 615 additions and 47 deletions

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ Build output is `build/libs/purpur-fantasy-stick-<version>.jar`. Server APIs, te
## Local event files
Fantasy Stick independently writes compact CloudEvents 1.0 JSON objects as UTF-8 JSONL under `<plugin data directory>/events/YYYY-MM-DD/events-<boot UUID>-<segment>.jsonl`. The initial foundation records plugin lifecycle/recovery and correlated observed/resolved native interactions for active characters: block/entity/item/inventory/vehicle/control use, item pickup/drop, held-slot changes and discrete teleports. It intentionally excludes movement/look ticks, rendering, particles and unrelated ordinary-player activity. It has no dependency on Event Producer, no network endpoint and no player-facing log reader.
Fantasy Stick independently writes compact CloudEvents 1.0 JSON objects as UTF-8 JSONL under `<plugin data directory>/events/YYYY-MM-DD/events-<boot UUID>-<segment>.jsonl`. The initial foundation records plugin lifecycle/recovery and correlated observed/resolved native interactions for active characters: block/entity/item/inventory/vehicle/control use, item pickup/drop, held-slot changes and discrete teleports. The downed feature additionally records durable downing/resolution facts, learned combat-Revive casts and results, accepted final-death/Tail transitions, prevented waiting/protection damage, protection expiry, and authorized downed-policy reads/changes. Stable episode/action identities and original deadlines, attribution, custody, locations, frozen rewards, caster cooldown/range/line-of-sight context survive recovery without inferring Phoenix Down use. It intentionally excludes movement/look ticks, rendering, particles and unrelated ordinary-player activity. It has no dependency on Event Producer, no network endpoint and no player-facing log reader.
A stable plugin-owned server UUID and per-lifetime boot/sequence identity distinguish records. Events rotate at UTC midnight, on each writer lifetime and before 128 MiB; an oversized record stays whole in its own segment. Accepted work is first retained in internal pending files and exported at least once with unchanged IDs, so consumers must deduplicate by `(source, id)`. Startup recovers pending work, quarantines malformed/interrupted tails outside `*.jsonl`, and reports incomplete prior lifetimes without inventing a shutdown. Queue overload and pre-durable native-observation crashes remain truthful loss windows; logging never rolls back or replays gameplay.
@@ -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();
@@ -12,16 +12,40 @@ class DownedSessionNativeTest{
@TempDir Path data;
@BeforeAll static void bootstrap()throws Exception{NativeRuntime.bootstrap();}
@Test void registeredAdminConfigurationReadsCompletesValidatesAndPublishesDownedPolicies()throws Exception{
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var sender=new EquipmentAdminCommandNativeTest.Sender();assertEquals(java.util.List.of("downed-timeout-seconds"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}));assertEquals(java.util.List.of("300"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds",""}));f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds"});assertTrue(sender.messages.getLast().contains("=300"));int before=sender.messages.size();f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","240"});while(sender.messages.size()==before){var task=f.tasks.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();}assertTrue(sender.messages.getLast().contains("=240"));var settings=(games.dmg.fantasystick.persistence.DownedSettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedSettings");assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","0"});assertTrue(sender.messages.getLast().contains("invalid"));assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","revive-downed-invulnerability-seconds","5","extra"});assertTrue(sender.messages.getLast().contains("Usage"));sender.allowed=false;assertTrue(f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}).isEmpty());assertTrue(java.nio.file.Files.readString(data.resolve("config.yml")).contains("downed-timeout-seconds: 240"));}
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var sender=new EquipmentAdminCommandNativeTest.Sender();assertEquals(java.util.List.of("downed-timeout-seconds"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}));assertEquals(java.util.List.of("300"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds",""}));f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds"});assertTrue(sender.messages.getLast().contains("=300"));int before=sender.messages.size();f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","240"});while(sender.messages.size()==before){var task=f.tasks.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();}assertTrue(sender.messages.getLast().contains("=240"));var settings=(games.dmg.fantasystick.persistence.DownedSettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedSettings");assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","0"});assertTrue(sender.messages.getLast().contains("invalid"));assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","revive-downed-invulnerability-seconds","5","extra"});assertTrue(sender.messages.getLast().contains("Usage"));sender.allowed=false;assertTrue(f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}).isEmpty());assertTrue(java.nio.file.Files.readString(data.resolve("config.yml")).contains("downed-timeout-seconds: 240"));f.plugin.setEnabled(false);var records=new java.util.ArrayList<com.google.gson.JsonObject>();try(var files=java.nio.file.Files.walk(data.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file))if(!line.isBlank())records.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}assertTrue(records.stream().anyMatch(event->event.get("type").getAsString().endsWith("config.read")&&event.getAsJsonObject("data").get("key").getAsString().equals("downed-timeout-seconds")));var changed=records.stream().filter(event->event.get("type").getAsString().endsWith("config.changed")).map(event->event.getAsJsonObject("data")).filter(event->event.get("key").getAsString().equals("downed-timeout-seconds")).findFirst().orElseThrow();assertEquals("300",changed.get("before").getAsString());assertEquals("240",changed.get("after").getAsString());}
}
@Test void restartClaimsAnExpiredEpisodeAsOneTimeoutResolutionWithoutInventingDeath() throws Exception {
var past=java.time.Instant.now().minus(java.time.Duration.ofMinutes(10));var character=UUID.randomUUID();
try(var directory=new games.dmg.fantasystick.session.DownedDirectory(data,java.time.Clock.fixed(past,java.time.ZoneOffset.UTC))){directory.begin(character,UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),0,64,0,0,0,java.time.Duration.ofMinutes(5),new games.dmg.fantasystick.session.DownedEpisode.Attribution(null,"minecraft:fall")).join();}
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.find(character).join().orElseThrow().phase()==games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(games.dmg.fantasystick.session.DownedEpisode.Phase.RESOLVED,directory.find(character).join().orElseThrow().phase());for(int attempt=0;attempt<20;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task==null)break;task.run();}f.plugin.setEnabled(false);}
var events=new java.util.ArrayList<com.google.gson.JsonObject>();try(var files=java.nio.file.Files.walk(data.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file))if(!line.isBlank())events.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}
var resolved=events.stream().filter(event->event.get("type").getAsString().endsWith("character.downed_resolved")).toList();assertEquals(1,resolved.size());assertEquals("timeout",resolved.getFirst().getAsJsonObject("data").get("outcome").getAsString());assertTrue(events.stream().noneMatch(event->event.get("type").getAsString().endsWith("character.died")));
}
@Test void restartReconcilesStableDownedResolutionAndExpiredProtectionEvents() throws Exception {
var character=UUID.randomUUID();
try(var directory=new games.dmg.fantasystick.session.DownedDirectory(data,java.time.Clock.systemUTC())){
var episode=directory.begin(character,UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),1,64,2,0,0,
java.time.Duration.ofMinutes(5),new games.dmg.fantasystick.session.DownedEpisode.Attribution(null,"minecraft:fall")).join();
var action=UUID.randomUUID();
var resolved=directory.claim(episode.id(),games.dmg.fantasystick.session.DownedEpisode.Outcome.REVIVED,action,
java.time.Duration.ZERO).join().episode().orElseThrow();
directory.publish(resolved.id(),action).join();
}
for(int boot=0;boot<2;boot++)try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);f.plugin.setEnabled(false);}
var ids=new java.util.ArrayList<String>();
try(var files=java.nio.file.Files.walk(data.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file)){if(line.isBlank())continue;var event=com.google.gson.JsonParser.parseString(line).getAsJsonObject();if(event.get("type").getAsString().endsWith("effect.ended"))ids.add(event.get("id").getAsString());}}
assertEquals(2,ids.size());assertEquals(ids.getFirst(),ids.getLast());
}
@Test void directProjectileOngoingAndEnvironmentalLethalCausesEnterTheSameDurablePhase()throws Exception{
var types=java.util.List.of(org.bukkit.damage.DamageType.PLAYER_ATTACK,org.bukkit.damage.DamageType.ARROW,org.bukkit.damage.DamageType.ON_FIRE,org.bukkit.damage.DamageType.FALL);int index=0;for(var type:types){var directory=data.resolve("cause-"+index++);java.nio.file.Files.createDirectories(directory);try(var f=new FantasyStickLifecycleNativeTest.Fixture(directory)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(directory);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;var death=death(actor,type);f.dispatcher.accept(death);var downed=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&downed.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(death.isCancelled());assertEquals(type.getKey().asString(),downed.all().getFirst().attribution().cause());}}
var types=java.util.List.of(org.bukkit.damage.DamageType.PLAYER_ATTACK,org.bukkit.damage.DamageType.ARROW,org.bukkit.damage.DamageType.ON_FIRE,org.bukkit.damage.DamageType.FALL);int index=0;for(var type:types){var directory=data.resolve("cause-"+index++);java.nio.file.Files.createDirectories(directory);try(var f=new FantasyStickLifecycleNativeTest.Fixture(directory)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(directory);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;var death=death(actor,type);f.dispatcher.accept(death);var downed=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&(downed.all().isEmpty()||actor.inventories.isEmpty());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(death.isCancelled());assertFalse(actor.inventories.isEmpty());assertEquals(type.getKey().asString(),downed.all().getFirst().attribution().cause());f.plugin.setEnabled(false);var events=new java.util.ArrayList<com.google.gson.JsonObject>();try(var files=java.nio.file.Files.walk(directory.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file))if(!line.isBlank())events.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}var recorded=events.stream().filter(event->event.get("type").getAsString().endsWith("character.downed")).map(event->event.getAsJsonObject("data")).findFirst().orElseThrow();assertEquals(type.getKey().asString(),recorded.get("lethal_cause").getAsString());}}
}
@Test void nativeLethalOutcomeEntersDurableDownedPhaseWithoutFinalDeathOrTail()throws Exception{
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.location.add(7,0,3);var anchor=actor.core.location.clone();actor.core.health=0;var death=death(actor);f.dispatcher.accept(death);actor.player.setHealth(death.getReviveHealth());var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(death.isCancelled());assertEquals(1d,actor.player.getHealth());var episode=directory.all().getFirst();assertEquals(actor.core.record.id(),episode.character());assertEquals(actor.core.id,episode.player());assertEquals(anchor.getWorld().getUID(),episode.world());assertEquals(anchor.getX(),episode.x());assertEquals(games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING,episode.phase());var characters=(games.dmg.fantasystick.persistence.CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");assertFalse(characters.find(actor.core.record.id()).join().orElseThrow().dead());assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");var active=sessions.active(actor.core.id).orElseThrow();assertFalse(sessions.current(active));assertTrue(sessions.downed(actor.core.id).isPresent());}
}
@Test void claimedReviveRestoresFullHealthInPlaceAndAddsBoundedDamageProtection()throws Exception{
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.location.add(4,0,2);var anchor=actor.core.location.clone();actor.core.health=0;f.dispatcher.accept(death(actor));var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");var outcome=new java.util.concurrent.atomic.AtomicReference<games.dmg.fantasystick.session.DownedController.RescueStatus>();for(int attempt=0;attempt<80&&!controller.downed(actor.player);attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}controller.revive(actor.player,java.time.Duration.ofSeconds(5),outcome::set);for(int attempt=0;attempt<80&&outcome.get()==null;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(games.dmg.fantasystick.session.DownedController.RescueStatus.APPLIED,outcome.get());assertEquals(actor.maximumHealth.getValue(),actor.player.getHealth());assertEquals(anchor,actor.player.getLocation());var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");assertTrue(sessions.current(sessions.active(actor.core.id).orElseThrow()));assertTrue(sessions.downedProtected(actor.core.id));assertFalse(new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().dead());var damage=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityDamageEvent.class);org.mockito.Mockito.when(damage.getEntity()).thenReturn(actor.player);controller.damage(damage);org.mockito.Mockito.verify(damage).setCancelled(true);assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());sessions.exit(actor.player);f.awaitCharacterAndReceipt(actor);sessions.arrive(actor.player);for(int attempt=0;attempt<120&&sessions.active(actor.core.id).isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(sessions.downedProtected(actor.core.id),"Reconnect retains the original absolute protection deadline");}
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.location.add(4,0,2);var anchor=actor.core.location.clone();actor.core.health=0;f.dispatcher.accept(death(actor));var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");var outcome=new java.util.concurrent.atomic.AtomicReference<games.dmg.fantasystick.session.DownedController.RescueStatus>();for(int attempt=0;attempt<80&&!controller.downed(actor.player);attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}controller.revive(actor.player,java.time.Duration.ofSeconds(5),outcome::set);for(int attempt=0;attempt<80&&outcome.get()==null;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(games.dmg.fantasystick.session.DownedController.RescueStatus.APPLIED,outcome.get());assertEquals(actor.maximumHealth.getValue(),actor.player.getHealth());assertEquals(anchor,actor.player.getLocation());var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");assertTrue(sessions.current(sessions.active(actor.core.id).orElseThrow()));assertTrue(sessions.downedProtected(actor.core.id));assertFalse(new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().dead());var damage=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityDamageEvent.class);org.mockito.Mockito.when(damage.getEntity()).thenReturn(actor.player);controller.damage(damage);org.mockito.Mockito.verify(damage).setCancelled(true);assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());sessions.exit(actor.player);f.awaitCharacterAndReceipt(actor);sessions.arrive(actor.player);for(int attempt=0;attempt<120&&sessions.active(actor.core.id).isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(sessions.downedProtected(actor.core.id),"Reconnect retains the original absolute protection deadline");f.plugin.setEnabled(false);var events=new java.util.ArrayList<com.google.gson.JsonObject>();try(var files=java.nio.file.Files.walk(data.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file))if(!line.isBlank())events.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}assertTrue(events.stream().filter(event->event.get("type").getAsString().endsWith("combat.prevented")).map(event->event.getAsJsonObject("data")).anyMatch(event->event.get("reason").getAsString().equals("revive_protection")));}
}
@Test void downedFreezeCancelsMotionCombatHealingHungerItemsAndInventoryMutation()throws Exception{
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;f.dispatcher.accept(death(actor));var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");for(int attempt=0;attempt<80&&(!controller.downed(actor.player)||actor.inventories.isEmpty());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}org.mockito.Mockito.verify(actor.player).setGravity(false);var from=actor.core.location.clone();var to=from.clone().add(1,0,0);var move=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerMoveEvent.class);org.mockito.Mockito.when(move.getPlayer()).thenReturn(actor.player);org.mockito.Mockito.when(move.getFrom()).thenReturn(from);org.mockito.Mockito.when(move.getTo()).thenReturn(to);controller.move(move);org.mockito.Mockito.verify(move).setTo(from);var velocity=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerVelocityEvent.class);org.mockito.Mockito.when(velocity.getPlayer()).thenReturn(actor.player);controller.velocity(velocity);org.mockito.Mockito.verify(velocity).setCancelled(true);var attack=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityDamageByEntityEvent.class);org.mockito.Mockito.when(attack.getDamager()).thenReturn(actor.player);controller.attack(attack);org.mockito.Mockito.verify(attack).setCancelled(true);var heal=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityRegainHealthEvent.class);org.mockito.Mockito.when(heal.getEntity()).thenReturn(actor.player);controller.heal(heal);org.mockito.Mockito.verify(heal).setCancelled(true);var hunger=org.mockito.Mockito.mock(org.bukkit.event.entity.FoodLevelChangeEvent.class);org.mockito.Mockito.when(hunger.getEntity()).thenReturn(actor.player);controller.hunger(hunger);org.mockito.Mockito.verify(hunger).setCancelled(true);var consume=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerItemConsumeEvent.class);org.mockito.Mockito.when(consume.getPlayer()).thenReturn(actor.player);controller.consume(consume);org.mockito.Mockito.verify(consume).setCancelled(true);var old=actor.core.inventory.getItem(4).clone();actor.core.inventory.setItem(4,new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIRT));var change=new io.papermc.paper.event.player.PlayerInventorySlotChangeEvent(actor.player,4,old,actor.core.inventory.getItem(4));((games.dmg.fantasystick.session.EquipmentSessionEvents)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessionEvents")).changed(change);assertTrue(((games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions")).active(actor.core.id).isPresent());controller.slot(change);var task=f.tasks.poll(1,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();assertEquals(old,actor.core.inventory.getItem(4));}
@@ -466,6 +466,18 @@ class FantasyStickLifecycleNativeTest {
f.tick();DownedSessionNativeTest.awaitTail(f,a);
assertTrue(a.messages.stream().anyMatch(message -> message.startsWith("§c")), "Red defeat feedback port");
f.plugin.setEnabled(false);
var records=new java.util.ArrayList<com.google.gson.JsonObject>();
try(var files=java.nio.file.Files.walk(directory.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList()){for(var line:java.nio.file.Files.readAllLines(file)){if(line.isBlank())continue;records.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}}}
var types=records.stream().map(event->event.get("type").getAsString()).toList();
assertTrue(types.contains("games.dmg.minecraft.fantasystick.character.downed"),types.toString());
assertEquals(1,types.stream().filter("games.dmg.minecraft.fantasystick.character.downed_resolved"::equals).count(),types.toString());
assertEquals(1,types.stream().filter("games.dmg.minecraft.fantasystick.character.died"::equals).count(),types.toString());
assertTrue(types.contains("games.dmg.minecraft.fantasystick.action.resolved"),types.toString());
var resolution=records.stream().filter(event->event.get("type").getAsString().endsWith("character.downed_resolved")).findFirst().orElseThrow().getAsJsonObject("data");
assertEquals("accept_death",resolution.get("outcome").getAsString());
assertEquals(a.core.record.id().toString(),resolution.get("actor_character_id").getAsString());
assertTrue(resolution.has("deadline"));assertTrue(resolution.has("lethal_cause"));
assertFalse(types.stream().anyMatch(type->type.contains("phoenix")),types.toString());
}
f.awaitWorkers(); sessions.drained().toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
assertEquals(!disable,new YamlCharacterRepository(directory).load(a.core.record.id()).orElseThrow().dead());
@@ -48,7 +48,7 @@ class ReviveNativeTest {
}
@Test void learnedAimedReviveRestoresAnyPartyDownedCharacterInPlace()throws Exception{
try(var fixture=new FantasyStickLifecycleNativeTest.Fixture(data)){fixture.plugin.setEnabled(true);var caster=new FantasyStickLifecycleNativeTest.Actor(data);withRevive(data,caster);var target=new FantasyStickLifecycleNativeTest.Actor(data);fixture.players.put(caster.core.id,caster.player);fixture.players.put(target.core.id,target.player);var worldId=java.util.UUID.randomUUID();org.mockito.Mockito.when(caster.world.getUID()).thenReturn(worldId);org.mockito.Mockito.when(target.world.getUID()).thenReturn(worldId);fixture.activate(caster);fixture.activate(target);caster.core.location.setWorld(caster.world);caster.core.location.setX(0);caster.core.location.setY(64);caster.core.location.setZ(0);target.core.location.setWorld(caster.world);target.core.location.setX(3);target.core.location.setY(64);target.core.location.setZ(0);var anchor=target.core.location.clone();org.mockito.Mockito.doReturn(true).when(caster.player).hasLineOfSight(target.player);target.core.health=0;var source=new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));fixture.dispatcher.accept(new org.bukkit.event.entity.PlayerDeathEvent(target.player,source,new java.util.ArrayList<>(),0,net.kyori.adventure.text.Component.empty(),true));var downed=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"downedController");for(int attempt=0;attempt<80&&!downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}caster.core.inventory.getInventory().setSelectedSlot(2);fixture.dispatcher.accept(new org.bukkit.event.player.PlayerInteractEntityEvent(caster.player,target.player,org.bukkit.inventory.EquipmentSlot.HAND));for(int attempt=0;attempt<120&&downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"sessions");assertFalse(downed.downed(target.player),()->"caster="+caster.messages+", target="+target.messages);assertTrue(sessions.current(sessions.active(target.core.id).orElseThrow()));assertEquals(target.maximumHealth.getValue(),target.player.getHealth());assertEquals(anchor,target.player.getLocation());assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,target.core.inventory.getItemInOffHand().getType());var casterRecord=sessions.currentRecord(sessions.active(caster.core.id).orElseThrow()).orElseThrow();assertTrue(casterRecord.cooldowns().get("revive").isAfter(java.time.Instant.now().plusSeconds(86300)));}
try(var fixture=new FantasyStickLifecycleNativeTest.Fixture(data)){fixture.plugin.setEnabled(true);var caster=new FantasyStickLifecycleNativeTest.Actor(data);withRevive(data,caster);var target=new FantasyStickLifecycleNativeTest.Actor(data);fixture.players.put(caster.core.id,caster.player);fixture.players.put(target.core.id,target.player);var worldId=java.util.UUID.randomUUID();org.mockito.Mockito.when(caster.world.getUID()).thenReturn(worldId);org.mockito.Mockito.when(target.world.getUID()).thenReturn(worldId);fixture.activate(caster);fixture.activate(target);caster.core.location.setWorld(caster.world);caster.core.location.setX(0);caster.core.location.setY(64);caster.core.location.setZ(0);target.core.location.setWorld(caster.world);target.core.location.setX(3);target.core.location.setY(64);target.core.location.setZ(0);var anchor=target.core.location.clone();org.mockito.Mockito.doReturn(true).when(caster.player).hasLineOfSight(target.player);target.core.health=0;var source=new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));fixture.dispatcher.accept(new org.bukkit.event.entity.PlayerDeathEvent(target.player,source,new java.util.ArrayList<>(),0,net.kyori.adventure.text.Component.empty(),true));var downed=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"downedController");for(int attempt=0;attempt<80&&!downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}caster.core.inventory.getInventory().setSelectedSlot(2);fixture.dispatcher.accept(new org.bukkit.event.player.PlayerInteractEntityEvent(caster.player,target.player,org.bukkit.inventory.EquipmentSlot.HAND));for(int attempt=0;attempt<120&&downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}for(int attempt=0;attempt<80&&caster.messages.stream().noneMatch(message->message.contains("restored the downed"));attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"sessions");assertFalse(downed.downed(target.player),()->"caster="+caster.messages+", target="+target.messages);assertTrue(sessions.current(sessions.active(target.core.id).orElseThrow()));assertEquals(target.maximumHealth.getValue(),target.player.getHealth());assertEquals(anchor,target.player.getLocation());assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,target.core.inventory.getItemInOffHand().getType());var casterRecord=sessions.currentRecord(sessions.active(caster.core.id).orElseThrow()).orElseThrow();assertTrue(casterRecord.cooldowns().get("revive").isAfter(java.time.Instant.now().plusSeconds(86300)));fixture.plugin.setEnabled(false);var records=new java.util.ArrayList<com.google.gson.JsonObject>();try(var files=java.nio.file.Files.walk(data.resolve("events"))){for(var file:files.filter(path->path.getFileName().toString().endsWith(".jsonl")).toList())for(var line:java.nio.file.Files.readAllLines(file))if(!line.isBlank())records.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject());}var types=records.stream().map(event->event.get("type").getAsString()).toList();assertTrue(types.contains("games.dmg.minecraft.fantasystick.ability.cast"),types.toString());assertTrue(types.contains("games.dmg.minecraft.fantasystick.ability.resolved"),types.toString());assertEquals(1,types.stream().filter("games.dmg.minecraft.fantasystick.character.downed_resolved"::equals).count(),types.toString());var resolutionEvent=records.stream().filter(event->event.get("type").getAsString().endsWith("character.downed_resolved")).findFirst().orElseThrow();var resolution=resolutionEvent.getAsJsonObject("data");assertEquals(caster.core.id.toString(),resolutionEvent.get("playerid").getAsString());assertEquals(caster.core.record.id().toString(),resolutionEvent.get("characterid").getAsString());assertEquals(caster.core.record.id().toString(),resolution.get("actor_character_id").getAsString());assertEquals(3.0,resolution.get("final_range").getAsDouble());assertTrue(resolution.get("line_of_sight").getAsBoolean());assertFalse(types.stream().anyMatch(type->type.contains("phoenix")||type.endsWith("character.revived")));}
}
@Test void ordinaryTargetSelectsOneTailAndReceivesTheSameLivingSheetOnce() throws Exception {
@@ -0,0 +1,116 @@
package games.dmg.fantasystick.events;
import static org.junit.jupiter.api.Assertions.*;
import games.dmg.fantasystick.session.DownedEpisode;
import java.math.BigInteger;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
final class DownedEventBridgeTest {
private static final Instant NOW = Instant.parse("2026-09-24T12:30:00Z");
@Test void durableEpisodeProducesStableCompleteDownedResolutionAndRecoveryRecords() {
var captured = new ArrayList<EventInput>();
var events = new DownedEventBridge(captured::add, Clock.fixed(NOW, ZoneOffset.UTC));
var pending = episode(DownedEpisode.Phase.PENDING, null, null, null, null, false);
var decision = new DownedEpisode.Decision("revive", UUID.randomUUID(), "CasterAccount", UUID.randomUUID(),
"Caster Character", UUID.randomUUID(), UUID.randomUUID(), NOW.minusSeconds(12), NOW.plus(Duration.ofHours(24)), 11.75, true);
var resolved = episode(DownedEpisode.Phase.RESOLVED, DownedEpisode.Outcome.REVIVED,
decision.actionId(), NOW.minusSeconds(10), NOW.minusSeconds(5), true, decision);
events.reconcile(List.of(pending, resolved));
var first = List.copyOf(captured);
events.reconcile(List.of(pending, resolved));
assertEquals(List.of("character.downed", "character.downed", "ability.cast",
"character.downed_resolved", "ability.resolved", "action.resolved", "effect.ended"),
first.stream().map(EventInput::type).toList());
assertEquals(first.stream().map(EventInput::id).toList(),
captured.subList(first.size(), captured.size()).stream().map(EventInput::id).toList());
var downed = first.getFirst();
assertEquals(pending.id().toString(), downed.data().get("episode_id"));
assertEquals(pending.character().toString(), downed.data().get("subject_character_id"));
assertEquals("Target Character", downed.data().get("subject_character_name"));
assertEquals(pending.player().toString(), downed.data().get("subject_player_id"));
assertEquals("TargetAccount", downed.data().get("subject_player_name"));
assertEquals(pending.session().toString(), downed.data().get("custody_session_id"));
assertEquals("19", downed.data().get("character_revision"));
assertEquals("minecraft:out_of_world", downed.data().get("lethal_cause"));
assertEquals("9007199254740993", downed.data().get("victim_coins"));
assertEquals("1.25", ((java.util.Map<?, ?>) downed.data().get("location")).get("x"));
assertEquals(decision.castAt(), first.get(2).time());
var resolution = first.get(3);
assertEquals("revive", resolution.data().get("outcome"));
assertEquals(decision.actorCharacter().toString(), resolution.data().get("actor_character_id"));
assertEquals(decision.actorPlayer(), resolution.context().playerId());
assertEquals(decision.actorCharacter(), resolution.context().characterId());
assertEquals(decision.cooldownUntil(), resolution.data().get("cooldown_until"));
assertEquals(11.75, resolution.data().get("final_range"));
assertEquals(true, resolution.data().get("line_of_sight"));
assertEquals("decision_won", first.get(4).data().get("outcome"));
assertEquals("completed", first.get(5).data().get("outcome"));
assertEquals(resolved.protectionUntil(), first.get(6).time());
assertFalse(first.stream().anyMatch(event -> event.type().contains("phoenix")));
}
@Test void publishedFinalDeathReconcilesTheSingleStableDeathFactAndFrozenRewards() {
var captured=new ArrayList<EventInput>();var events=new DownedEventBridge(captured::add,Clock.fixed(NOW,ZoneOffset.UTC));
var operation=UUID.randomUUID();var downed=NOW.minusSeconds(100);var deadline=NOW.minusSeconds(2);
var episode=new DownedEpisode(UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),
1,64,2,0,0,UUID.randomUUID(),4,70,5,0,0,downed,deadline,
new DownedEpisode.Attribution(UUID.randomUUID(),"minecraft:player_attack",true,List.of(UUID.randomUUID()),8,BigInteger.valueOf(91)),
"Dead Character","DeadAccount",BigInteger.valueOf(22),DownedEpisode.Phase.RESOLVED,DownedEpisode.Outcome.FINAL_DEATH,operation,deadline,null,
new DownedEpisode.Decision("timeout",null,null,null,null,null,operation,null,null,null,null),
List.of(new DownedEpisode.Reward(UUID.randomUUID(),BigInteger.TEN,BigInteger.valueOf(4))),true);
events.reconcile(List.of(episode));var first=List.copyOf(captured);events.reconcile(List.of(episode));
assertEquals(List.of("character.downed","character.downed_resolved","character.died","action.resolved"),first.stream().map(EventInput::type).toList());
assertEquals(first.stream().map(EventInput::id).toList(),captured.subList(first.size(),captured.size()).stream().map(EventInput::id).toList());
assertEquals("timeout",first.get(1).data().get("outcome"));
assertEquals("91",first.get(2).data().get("victim_coins"));
assertEquals("4",((java.util.Map<?,?>)((java.util.List<?>)first.get(1).data().get("final_rewards")).getFirst()).get("coins"));
}
@Test void transientPreventionAndConfigFactsRemainTruthfulAndLoggingFailureCannotEscape() {
var captured = new ArrayList<EventInput>();
var events = new DownedEventBridge(captured::add, Clock.fixed(NOW, ZoneOffset.UTC));
var pending = episode(DownedEpisode.Phase.PENDING, null, null, null, null, false);
events.prevented(pending, "downed_waiting", 7.5);
events.configRead("console", null, null, "downed-timeout-seconds", "300");
events.configChanged("player", UUID.randomUUID(), "Admin", "revive-downed-invulnerability-seconds", "5", "7");
assertEquals(List.of("combat.prevented", "config.read", "config.changed"),
captured.stream().map(EventInput::type).toList());
assertEquals("7.5", captured.getFirst().data().get("prevented_amount"));
assertDoesNotThrow(() -> new DownedEventBridge(input -> { throw new IllegalStateException("disk"); },
Clock.fixed(NOW, ZoneOffset.UTC)).downed(pending));
}
private static DownedEpisode episode(DownedEpisode.Phase phase, DownedEpisode.Outcome outcome,
UUID operation, Instant resolvedAt, Instant protectionUntil, boolean published) {
return episode(phase, outcome, operation, resolvedAt, protectionUntil, published, null);
}
private static DownedEpisode episode(DownedEpisode.Phase phase, DownedEpisode.Outcome outcome,
UUID operation, Instant resolvedAt, Instant protectionUntil, boolean published,
DownedEpisode.Decision decision) {
var downed = NOW.minusSeconds(100);
return new DownedEpisode(UUID.fromString("00000000-0000-0000-0000-000000000101"),
UUID.fromString("00000000-0000-0000-0000-000000000102"),
UUID.fromString("00000000-0000-0000-0000-000000000103"),
UUID.fromString("00000000-0000-0000-0000-000000000104"),
UUID.fromString("00000000-0000-0000-0000-000000000105"),
1.25, 64.5, -9.75, 3.0f, 4.0f,
UUID.fromString("00000000-0000-0000-0000-000000000106"),
10.5, 70.0, 12.5, 8.0f, 9.0f, downed, downed.plusSeconds(98),
new DownedEpisode.Attribution(UUID.fromString("00000000-0000-0000-0000-000000000107"),
"minecraft:out_of_world", true, List.of(UUID.fromString("00000000-0000-0000-0000-000000000108")),
12, new BigInteger("9007199254740993")), "Target Character", "TargetAccount", BigInteger.valueOf(19), phase, outcome, operation,
resolvedAt, protectionUntil, decision, List.of(), published);
}
}
@@ -42,6 +42,29 @@ class DownedDirectoryTest {
}
}
@Test void preservesCharacterRevisionAndWinningReviveDecisionAcrossRestart() throws Exception {
var clock=Clock.fixed(Instant.parse("2026-09-24T12:40:00Z"),ZoneOffset.UTC);
var action=UUID.randomUUID();
var decision=new DownedEpisode.Decision("revive",UUID.randomUUID(),"CasterAccount",UUID.randomUUID(),"Caster Character",UUID.randomUUID(),action,
clock.instant(),clock.instant().plus(Duration.ofHours(24)),11.5,true);
UUID character=UUID.randomUUID();
try(var directory=new DownedDirectory(data,clock)){
var episode=directory.begin(character,UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),1,2,3,4,5,
UUID.randomUUID(),6,7,8,9,10,"Target Character","TargetAccount",java.math.BigInteger.valueOf(42),Duration.ofMinutes(5),
new DownedEpisode.Attribution(null,"ENVIRONMENT")).join();
assertEquals(java.math.BigInteger.valueOf(42),episode.characterRevision());
assertEquals("Target Character",episode.characterName());assertEquals("TargetAccount",episode.playerName());
var resolved=directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,action,decision,
Duration.ofSeconds(5),java.util.List.of()).join().episode().orElseThrow();
assertEquals(decision,resolved.decision());
}
try(var directory=new DownedDirectory(data,clock)){
var restored=directory.find(character).join().orElseThrow();
assertEquals(java.math.BigInteger.valueOf(42),restored.characterRevision());
assertEquals(decision,restored.decision());
}
}
@Test void concurrentRescueAndDeathClaimsPublishExactlyOneDurableWinner()throws Exception{
var clock=Clock.fixed(Instant.parse("2026-09-24T01:30:00Z"),ZoneOffset.UTC);
try(var directory=new DownedDirectory(data,clock)){