feat(fantasy-stick): complete audited gameplay follow-ups
Release / release (push) Failing after 1h34m22s

This commit is contained in:
dmg committed 2026-10-06 14:16:46 -04:00
1 parent 34e02860c0
commit a040115275
86 files changed
+9378 -760

No files matched your search

@@ -182,6 +182,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
private games.dmg.fantasystick.events.RecoveryEventBridge recoveryEvents;
private java.util.concurrent.CompletionStage<Void> recoveryAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.ReviveEventBridge reviveEvents;
private games.dmg.fantasystick.events.AdminActionEventBridge adminActionEvents;
private games.dmg.fantasystick.events.AdminCommandEntryObserver adminActionObserver;
private java.util.concurrent.CompletionStage<Void> adminActionDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.AdminRevivalEventBridge adminRevivalEvents;
private java.util.concurrent.CompletionStage<Void> adminRevivalAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.PartyEventBridge partyAuditEvents;
@@ -1120,6 +1123,17 @@ public final class FantasyStickPlugin extends JavaPlugin {
failure -> getLogger().log(Level.WARNING, "Recipe discovery event intent failed", failure));
recipeDiscovery.attachEvents(recipeEvents);
eventLog.ready(); // Queue startup recovery before any recipe event handoff.
adminActionEvents = new games.dmg.fantasystick.events.AdminActionEventBridge(
eventLog::emit, Clock.systemUTC(), getDataFolder().toPath(), sessions,
failure -> getLogger().log(Level.WARNING, "Admin action event intent failed", failure));
admin.attachAdminAudit(adminActionEvents);
adminActionObserver = new games.dmg.fantasystick.events.AdminCommandEntryObserver(adminCommand, adminActionEvents);
getServer().getPluginManager().registerEvents(adminActionObserver, this);
var replayAdminActions = adminActionEvents;
adminActionDrain.whenComplete((ignored, failure) -> {
if (failure != null) getLogger().log(Level.WARNING, "Previous admin action intent drain failed", failure);
replayAdminActions.replay();
});
var replayNutritionEvents = nutritionAuditEvents;
nutritionAuditDrain.whenComplete((ignored, failure) -> {
if (failure != null) getLogger().log(Level.WARNING, "Previous nutrition event intent drain failed", failure);
@@ -1286,6 +1300,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
var closingProtocol = protocolPresentation; protocolPresentation = null;
var closingChat = chatNames; chatNames = null;
var closingAdmin = admin; admin = null;
var closingAdminActionEvents = adminActionEvents; adminActionEvents = null;
var closingAdminActionObserver = adminActionObserver; adminActionObserver = null;
var closingCharacterRecovery = characterRecovery; characterRecovery = null;
var closingFeedbackCommand = feedbackCommand; feedbackCommand = null;
var closingParticlesCommand = particlesCommand; particlesCommand = null;
@@ -1874,13 +1890,43 @@ public final class FantasyStickPlugin extends JavaPlugin {
closingRareEvents.close();return null;
}).thenCompose(ignored -> closingRareEvents.drained());
});
if (closingEventLog != null) cleanup("local events", closingEventLog::close);
if (closingAdminActionEvents != null) cleanup("admin action event intent drain", () -> {
closingAdminActionEvents.close();
adminActionDrain = closingAdminActionEvents.drained();
});
if (closingEventLog != null) cleanup("local events", () -> {
// Preserve synchronous writer shutdown/lock release at disable return. Only the central
// handoff is awaited here; no all-owner sink-acknowledgment guarantee is implied.
var handoff = adminActionDrain;
var writerClosed = new java.util.concurrent.CompletableFuture<Void>();
adminActionDrain = writerClosed;
Throwable handoffFailure = null;
try {
handoff.toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
handoffFailure = interrupted;
} catch (java.util.concurrent.ExecutionException | java.util.concurrent.TimeoutException unavailable) {
handoffFailure = unavailable;
}
if (handoffFailure != null)
getLogger().log(Level.WARNING, "Central administrator audit handoff did not drain", handoffFailure);
try {
closingEventLog.close();
if (handoffFailure == null) writerClosed.complete(null);
else writerClosed.completeExceptionally(handoffFailure);
} catch (RuntimeException | Error failure) {
writerClosed.completeExceptionally(failure);
throw failure;
}
});
// Writer shutdown can still acknowledge already accepted preference exports.
if (closingFeedbackPreferences != null) cleanup("feedback preferences", closingFeedbackPreferences::close);
if (closingVitals != null) cleanup("native health hooks", closingVitals::close);
unregister(closingModes);
unregister(closingChat);
unregister(closingEventCapture);
unregister(closingAdminActionObserver);
unregister(closingMessageAuditEvents);
unregister(closingPartyEvents);
unregister(closingPartyCombat);
@@ -30,22 +30,22 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
/** Deterministic bounded four-target lightning chain with exact decimal decay. */
/** Deterministic INT-scaled bounded lightning chain with exact decimal decay. */
public final class ChainLightning implements AbilityEffect, Listener, AutoCloseable {
public record Settings(BigInteger baseDamage, Duration cooldown, double initialRange, double jumpRange,
int additionalTargets, BigDecimal jumpMultiplier) {
int additionalTargets, BigDecimal jumpMultiplier, BigInteger targetIntStep, int maxTargets) {
public Settings {
Objects.requireNonNull(baseDamage); Objects.requireNonNull(cooldown); Objects.requireNonNull(jumpMultiplier);
Objects.requireNonNull(baseDamage); Objects.requireNonNull(cooldown); Objects.requireNonNull(jumpMultiplier); Objects.requireNonNull(targetIntStep);
if (baseDamage.signum() < 0 || cooldown.isNegative() || cooldown.compareTo(Duration.ofDays(365)) > 0
|| !Double.isFinite(initialRange) || initialRange <= 0 || initialRange > 64
|| !Double.isFinite(jumpRange) || jumpRange <= 0 || jumpRange > 64
|| additionalTargets < 0 || additionalTargets > 63
|| additionalTargets < 0 || additionalTargets > 63 || targetIntStep.signum() <= 0 || maxTargets < 1 || maxTargets > 64
|| jumpMultiplier.signum() <= 0 || jumpMultiplier.compareTo(BigDecimal.ONE) > 0) {
throw new IllegalArgumentException("Invalid Chain Lightning settings");
}
}
public static Settings defaults() {
return new Settings(BigInteger.valueOf(8), Duration.ofSeconds(18), 16, 6, 3, new BigDecimal("0.75"));
return new Settings(BigInteger.valueOf(8), Duration.ofSeconds(18), 16, 6, 4, new BigDecimal("0.75"), BigInteger.valueOf(5), 12);
}
}
private static final class Attempt {
@@ -82,8 +82,9 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
public AbilityDefinition definition() {
var current = settings;
return new AbilityDefinition("chain_lightning", "Chain Lightning", Material.LIGHTNING_ROD,
List.of("Strike for " + current.baseDamage() + " + INT modifier damage, then jump up to "
+ current.additionalTargets() + " times.",
List.of("Strike for " + current.baseDamage() + " + INT modifier damage, with "
+ Math.min(current.maxTargets(), 1 + current.additionalTargets()) + " base total targets at INT 20.",
"Gain one target per " + current.targetIntStep() + " purchased INT above 20, capped at " + current.maxTargets() + " total targets.",
"Each jump deals " + decimal(current.jumpMultiplier().movePointRight(2))
+ "% of the previous defined damage within " + decimal(BigDecimal.valueOf(current.jumpRange())) + " blocks."),
"Use while aiming at the first visible hostile within " + decimal(BigDecimal.valueOf(current.initialRange())) + " blocks.",
@@ -93,7 +94,8 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
"initial-range", BigDecimal.valueOf(current.initialRange()).stripTrailingZeros(),
"jump-range", BigDecimal.valueOf(current.jumpRange()).stripTrailingZeros(),
"additional-targets", BigDecimal.valueOf(current.additionalTargets()),
"jump-multiplier", current.jumpMultiplier()), AbilityDefinition.TargetPolicy.SELECTION, this);
"jump-multiplier", current.jumpMultiplier(),
"target-int-step", new BigDecimal(current.targetIntStep()), "max-targets", BigDecimal.valueOf(current.maxTargets())), AbilityDefinition.TargetPolicy.SELECTION, this);
}
public static BigInteger initialDamage(BigInteger intelligence) { return initialDamage(BigInteger.valueOf(8), intelligence); }
@@ -105,6 +107,13 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
return base.add(modifier);
}
public static int targetBudget(BigInteger intelligence, Settings captured) {
Objects.requireNonNull(intelligence); Objects.requireNonNull(captured);
var earned = intelligence.subtract(BigInteger.valueOf(20)).max(BigInteger.ZERO).divide(captured.targetIntStep());
return earned.add(BigInteger.valueOf(1L + captured.additionalTargets()))
.min(BigInteger.valueOf(captured.maxTargets())).intValueExact();
}
@Override public boolean accepts(ControlInput input) {
return !closed && selectInitial(input, settings.initialRange()) != null;
}
@@ -117,7 +126,7 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
BigDecimal defined = new BigDecimal(initialDamage(captured.baseDamage(), execution.character().stats().get(Stat.INT)));
var visited = new HashSet<UUID>(); LivingEntity current = initial, previous = null;
var chainId = UUID.randomUUID(); int attempted = 0, accepted = 0;
int maximum = Math.min(64, 1 + captured.additionalTargets());
int maximum = targetBudget(execution.character().stats().get(Stat.INT), captured);
for (int hop = 0; hop < maximum && current != null && execution.stillCurrent(); hop++) {
if (!visited.add(current.getUniqueId()) || !eligible(caster, current)) break;
var attempt = strike(execution, caster, current, defined, chainId, hop + 1, previous);
@@ -254,7 +263,8 @@ public final class ChainLightning implements AbilityEffect, Listener, AutoClosea
private static Settings from(AbilityDefinition definition) {
var p = definition.parameters();
return new Settings(p.get("base-damage").toBigIntegerExact(), definition.cooldown(), p.get("initial-range").doubleValue(),
p.get("jump-range").doubleValue(), p.get("additional-targets").intValueExact(), p.get("jump-multiplier"));
p.get("jump-range").doubleValue(), p.get("additional-targets").intValueExact(), p.get("jump-multiplier"),
p.get("target-int-step").toBigIntegerExact(), p.get("max-targets").intValueExact());
}
private static String decimal(BigDecimal value) { return value.stripTrailingZeros().toPlainString(); }
@Override public void close() { closed = true; damaging = null; }
@@ -47,7 +47,7 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
}
}
public static Settings defaults() {
return new Settings(BigInteger.valueOf(4), Duration.ofSeconds(5), 32, Duration.ofSeconds(5),
return new Settings(BigInteger.valueOf(4), Duration.ofSeconds(5), 48, Duration.ofSeconds(5),
3, 0, Duration.ofSeconds(2));
}
}
@@ -150,7 +150,7 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
public AbilityDefinition definition() {
var current = settings;
return new AbilityDefinition("frost_shard", "Frost Shard", Material.PRISMARINE_SHARD,
List.of("Launch a bounded frost projectile.",
List.of("Launch a frost projectile with a " + BigDecimal.valueOf(current.range()).stripTrailingZeros().toPlainString() + "-block travel limit.",
"Deals " + current.baseDamage() + " + INT modifier damage and Slowness "
+ level(current.slownessAmplifier()) + " for " + seconds(current.slownessDuration()) + "s."),
"Use the equipped shard; a miss still spends the cooldown.",
@@ -31,36 +31,48 @@ public final class AdventureAdminTeleport {
}
public void teleport(CommandSender sender,String route,Target expected,Supplier<Optional<Target>> current){
teleport(sender,route,expected,current,status->{});
}
public void teleport(CommandSender sender,String route,Target expected,Supplier<Optional<Target>> current,
Consumer<games.dmg.fantasystick.events.AdminActionEventBridge.Outcome> resolved){
Objects.requireNonNull(resolved);
Objects.requireNonNull(sender);Objects.requireNonNull(route);Objects.requireNonNull(expected);Objects.requireNonNull(current);
if(!(sender instanceof Player player)){sender.sendMessage(route+" teleport requires a player.");return;}
if(!(sender instanceof Player player)){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED);sender.sendMessage(route+" teleport requires a player.");return;}
World world=server.getWorld(expected.world());
if(world==null){sender.sendMessage(route+" teleport refused: destination world is unavailable.");return;}
if(world==null){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED);sender.sendMessage(route+" teleport refused: destination world is unavailable.");return;}
CompletableFuture<?> loading;
try{loading=world.getChunkAtAsync(section(expected.x()),section(expected.z()));}
catch(RuntimeException failure){sender.sendMessage(route+" teleport failed; your location is unchanged.");return;}
catch(RuntimeException failure){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED);sender.sendMessage(route+" teleport failed; your location is unchanged.");return;}
loading.whenComplete((chunk,loadFailure)->schedule(()->{
if(loadFailure!=null){player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
if(!currentPlayer(player)){player.sendMessage(route+" teleport refused: permission or player session changed.");return;}
if(loadFailure!=null){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED);player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
if(!currentPlayer(player)){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED);player.sendMessage(route+" teleport refused: permission or player session changed.");return;}
var fresh=current.get();
if(fresh.isEmpty()||!fresh.orElseThrow().equals(expected)){
player.sendMessage(route+" teleport refused: destination changed or is no longer registered.");return;
resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED);player.sendMessage(route+" teleport refused: destination changed or is no longer registered.");return;
}
World currentWorld=server.getWorld(expected.world());
if(currentWorld==null||currentWorld!=world){player.sendMessage(route+" teleport refused: destination world is unavailable.");return;}
if(currentWorld==null||currentWorld!=world){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED);player.sendMessage(route+" teleport refused: destination world is unavailable.");return;}
var facing=player.getLocation();
var destination=new Location(world,expected.x(),expected.y(),expected.z(),
expected.preserveFacing()?facing.getYaw():expected.yaw(),expected.preserveFacing()?facing.getPitch():expected.pitch());
CompletableFuture<Boolean> moving;
try{moving=player.teleportAsync(destination);}
catch(RuntimeException failure){player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
moving.whenComplete((moved,moveFailure)->schedule(()->{
if(moveFailure!=null||!Boolean.TRUE.equals(moved)){player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
if(player.isOnline())player.sendMessage("Teleported to "+expected.name()+" ("+expected.type()+") at "+locations.format(expected.world(),expected.x(),expected.y(),expected.z())+".");
}));
}));
catch(RuntimeException failure){resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED);player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
moving.whenComplete((moved,moveFailure)->{
boolean completed=moveFailure==null&&Boolean.TRUE.equals(moved);
// The captured immutable action resolves from the native future, not feedback delivery.
resolved.accept(completed?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED);
schedule(()->{
if(!completed){player.sendMessage(route+" teleport failed; your location is unchanged.");return;}
if(player.isOnline())player.sendMessage("Teleported to "+expected.name()+" ("+expected.type()+") at "+locations.format(expected.world(),expected.x(),expected.y(),expected.z())+".");
});
});
},()->resolved.accept(games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED)));
}
private boolean currentPlayer(Player player){return player.isOnline()&&player.hasPermission(PERMISSION)&&server.getPlayer(player.getUniqueId())==player;}
private void schedule(Runnable task){try{nextTick.accept(task);}catch(RuntimeException ignored){}}
private void schedule(Runnable task){schedule(task,()->{});}
private void schedule(Runnable task,Runnable rejected){try{nextTick.accept(task);}catch(RuntimeException unavailable){rejected.run();}}
private static int section(double coordinate){return((int)Math.floor(coordinate))>>4;}
}
@@ -12,18 +12,100 @@ public final class AdventureQuestCommands {
private static final String PERMISSION="fantasystick.admin";
private final Plugin plugin;private final AdventureQuestDirectory directory;private final AdventureQuestController controller;private final Consumer<Runnable> nextTick;private final AdventureLocationPresentation locations;private final AdventureAdminTeleport teleports;
public AdventureQuestCommands(Plugin plugin,AdventureQuestDirectory directory,AdventureQuestController controller,Consumer<Runnable> nextTick){this.plugin=Objects.requireNonNull(plugin);this.directory=Objects.requireNonNull(directory);this.controller=Objects.requireNonNull(controller);this.nextTick=Objects.requireNonNull(nextTick);locations=new AdventureLocationPresentation(plugin.getServer());teleports=new AdventureAdminTeleport(plugin,nextTick);}
private games.dmg.fantasystick.events.AdminActionEventBridge adminAudit;
// Warning requests are only linked to an explicit confirmation by the same live sender.
private final Map<CommandSender,games.dmg.fantasystick.events.AdminActionEventBridge.Action> rerollWarnings=new WeakHashMap<>();
public void attachAdminAudit(games.dmg.fantasystick.events.AdminActionEventBridge bridge){adminAudit=Objects.requireNonNull(bridge);}
private void completedRead(games.dmg.fantasystick.events.AdminActionEventBridge.Action action){if(adminAudit!=null)adminAudit.result(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"read_completed",Map.of());}
private void outcome(games.dmg.fantasystick.events.AdminActionEventBridge.Action action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome status, String reason, UUID operation, UUID subject){
if(adminAudit==null)return;
var facts=new LinkedHashMap<String,Object>();
if(operation!=null)facts.put("domain_operation_id",operation);
if(subject!=null)facts.put("subject_id",subject);
adminAudit.result(action,status,reason,facts);
}
private void refused(){outcome(adminAudit==null?null:adminAudit.current(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);}
private void invalid(){outcome(adminAudit==null?null:adminAudit.current(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"invalid_arguments",null,null);}
private void saved(games.dmg.fantasystick.events.AdminActionEventBridge.Action action,Throwable failure,boolean applied,UUID operation,UUID subject){
outcome(action,failure!=null?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED:applied?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,failure!=null?"operation_failed":applied?"acknowledged":"owner_refused",applied?operation:null,applied?subject:null);
}
private games.dmg.fantasystick.events.FishingEventBridge fishingEvents;
public void attachFishingEvents(games.dmg.fantasystick.events.FishingEventBridge value){fishingEvents=Objects.requireNonNull(value);}
private games.dmg.fantasystick.events.CampEventBridge campEvents;
public void attachCampEvents(games.dmg.fantasystick.events.CampEventBridge value){campEvents=Objects.requireNonNull(value);}
private games.dmg.fantasystick.events.ChampionEventBridge championEvents;
public void attachChampionEvents(games.dmg.fantasystick.events.ChampionEventBridge value){championEvents=Objects.requireNonNull(value);}
public void adventure(CommandSender sender,String[] args){if(args.length==1){if(sender instanceof Player player)controller.inspect(player);else sender.sendMessage("Usage: /fstick adventure");return;}if(args.length==2&&args[1].equals("tracking")){if(sender instanceof Player player)controller.tracking(player,null);else sender.sendMessage("Quest tracking requires a player.");return;}if(args.length==3&&args[1].equals("tracking")&&(args[2].equals("on")||args[2].equals("off"))){if(sender instanceof Player player)controller.tracking(player,args[2].equals("on"));else sender.sendMessage("Quest tracking requires a player.");return;}if(args.length==2&&args[1].equals("reroll")){if(!authorized(sender))return;sender.sendMessage("Reroll expires every current adventure quest, encounter and reward claim. Run /fstickadmin adventure reroll confirm to reset the day.");return;}if(args.length!=3||!args[1].equals("reroll")||!args[2].equals("confirm")){sender.sendMessage("Usage: /fstick adventure [tracking [on|off]] or /fstickadmin adventure reroll [confirm]");return;}if(!authorized(sender))return;var current=directory.snapshot().catalog();UUID expected=current==null?null:current.revision();var campAudit=campEvents;var actor=campAudit==null?null:campAudit.actor(sender,null);directory.rerollToday(expected,actor).whenComplete((result,failure)->respond(sender,()->{if(failure!=null){sender.sendMessage("Adventure reset failed; the current generation is unchanged.");return;}switch(result.status()){case STALE->sender.sendMessage("Adventure reset refused: the generation changed or is still being published; inspect it and try again.");case APPLIED->{var catalog=result.catalog().orElseThrow();controller.publishPendingReset().whenComplete((published,publishFailure)->respond(sender,()->{if(publishFailure!=null||!published){sender.sendMessage("Adventure reset is saved but pending recovery; the new generation is not yet available.");return;}sender.sendMessage("Reset daily adventures: generation="+catalog.revision()+", offers="+catalog.sites().size()+", expires="+catalog.expiresAt()+".");}));}}}));}
public void site(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){usageSite(sender);return;}switch(args[1]){case"list"->{if(args.length!=2){usageSite(sender);return;}if(directory.snapshot().sites().stream().noneMatch(v->v.type()!=AdventureQuestState.SiteType.DUNGEON))sender.sendMessage("No adventure sites registered.");else directory.snapshot().sites().stream().filter(v->v.type()!=AdventureQuestState.SiteType.DUNGEON).sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.type().name().toLowerCase(Locale.ROOT)+" "+v.displayName()+" at "+locations.format(v.world(),v.x(),v.y(),v.z())+"; "+controller.arena(v).display()+"; mode="+v.participationMode().value()+siteDetails(v)));}case"place"->{if(args.length<3||!(sender instanceof Player player)){usageSite(sender);return;}if(args[2].equals("fishing")){placeFishing(sender,player,args);return;}if(!(args[2].equals("camp")||args[2].equals("champion"))){usageSite(sender);return;}int start=3;var mode=AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;if(args.length>3&&args[3].equals("--mode")){if(args.length<5){usageSite(sender);return;}try{mode=AdventureQuestState.ParticipationMode.parse(args[4]);}catch(IllegalArgumentException invalid){usageSite(sender);return;}start=5;}var placement=placement(args,start);if(placement==null){usageSite(sender);return;}var location=player.getLocation();var type=args[2].equals("camp")?AdventureQuestState.SiteType.CAMP:AdventureQuestState.SiteType.CHAMPION;var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,location);UUID operation=UUID.randomUUID();directory.placeSite(type,placement.name(),Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),placement.arena(),mode).whenComplete((value,failure)->{try{if(failure==null){if(campAudit!=null)campAudit.siteRegistered(operation,campActor,value,controller.arena(value));if(championEvents!=null)championEvents.siteRegistered(operation,campActor,value,controller.arena(value));}}catch(RuntimeException ignored){}respond(sender,()->sender.sendMessage(failure==null?"Placed "+value.type().name().toLowerCase(Locale.ROOT)+" "+value.id()+" ("+value.displayName()+") at "+locations.format(value.world(),value.x(),value.y(),value.z())+"; "+controller.arena(value).display()+"; mode="+value.participationMode().value()+".":"Adventure site save failed; desired state is unchanged."));});}case"fishing"->{fishing(sender,args);}case"mode"->{if(args.length<3||args.length>4){usageSite(sender);return;}UUID id=parse(args[2]);var current=id==null?null:site(id).orElse(null);if(current==null){sender.sendMessage("Adventure site not found.");return;}if(args.length==3){sender.sendMessage("Adventure site "+id+" mode="+current.participationMode().value()+".");return;}AdventureQuestState.ParticipationMode requested;try{requested=AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){usageSite(sender);return;}var audit=fishingEvents;var auditActor=audit==null?null:audit.actor(sender);var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,null);UUID operation=UUID.randomUUID();directory.setSiteMode(id,current.participationMode(),requested).whenComplete((result,failure)->{try{if(failure==null&&result.status()==AdventureQuestDirectory.ModeStatus.APPLIED){if(campAudit!=null)campAudit.siteModeChanged(operation,campActor,current,result.site().orElseThrow(),controller.arena(result.site().orElseThrow()));if(championEvents!=null)championEvents.siteModeChanged(operation,campActor,current,result.site().orElseThrow(),controller.arena(result.site().orElseThrow()));}}catch(RuntimeException ignored){}if(audit!=null&&current.type()==AdventureQuestState.SiteType.FISHING&&failure==null&&result.status()==AdventureQuestDirectory.ModeStatus.APPLIED)audit.site("adventure.site.mode_changed",UUID.randomUUID(),auditActor,result.site().orElseThrow(),Map.of("mode_before",current.participationMode().value(),"mode_after",requested.value()));respond(sender,()->{if(failure!=null){sender.sendMessage("Adventure site mode save failed; the acknowledged mode is unchanged.");return;}sender.sendMessage(switch(result.status()){case APPLIED->"Updated adventure site "+id+" mode="+result.site().orElseThrow().participationMode().value()+" for future acceptances.";case UNCHANGED->"Adventure site "+id+" mode is already "+requested.value()+".";case STALE->"Adventure site mode update refused: the acknowledged mode changed; inspect and retry.";case NOT_FOUND->"Adventure site not found.";});});});}case"remove"->{if(args.length!=3){usageSite(sender);return;}UUID id=parse(args[2]);if(id==null){usageSite(sender);return;}var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,null);UUID operation=UUID.randomUUID();directory.removeSite(id).whenComplete((removed,failure)->{try{if(failure==null&&removed.isPresent()){if(campAudit!=null)camLine truncated
public void giver(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){usageGiver(sender);return;}switch(args[1]){case"list"->{if(args.length!=2){usageGiver(sender);return;}if(directory.snapshot().givers().isEmpty())sender.sendMessage("No Quest Givers registered.");else directory.snapshot().givers().stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.displayName()+" at "+locations.format(v.world(),v.x(),v.y(),v.z())));}case"place"->{if(!(sender instanceof Player player)){usageGiver(sender);return;}String name=join(args,2);var location=player.getLocation();var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,location);UUID operation=UUID.randomUUID();directory.placeGiver(name,Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch()).whenComplete((value,failure)->respond(sender,()->{if(failure!=null){sender.sendMessage("Quest Giver save failed; desired state is unchanged.");return;}var observed=controller.observedGiver(value);boolean nativeReturned=false;try{var world=plugin.getServer().getWorld(value.world());if(world!=null&&world.isChunkLoaded(section(value.x()),section(value.z())))controller.reconcile(world.getChunkAt(section(value.x()),section(value.z())));nativeReturned=true;}finally{auditGiver(campAudit,"adventure.quest_giver.placed",operation,campActor,value,observed,nativeReturned);}sender.sendMessage("Placed Quest Giver "+value.id()+" ("+value.displayName()+") at "+locations.format(value.world(),value.x(),value.y(),value.z())+".");}));}case"remove"->{if(args.length!=3){usageGiver(sender);return;}UUID id=parse(args[2]);if(id==null){usageGiver(sender);return;}var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,null);UUID operation=UUID.randomUUID();directory.removeGiver(id).whenComplete((removed,failure)->respond(sender,()->{if(failure!=null)sender.sendMessage("Quest Giver removal failed; desired state is unchanged.");else if(removed.isEmpty())sender.sendMessage("Quest Giver not found.");else{var value=removed.orElseThrow();var observed=controller.observedGiver(value);boolean nativeReturned=false;try{controller.removeGiverLoaded(id);nativeReturned=true;}finally{auditGiver(campAudit,"adventure.quest_giver.removed",operation,campActor,value,observed,nativeReturned);}sender.sendMessage("Removed Quest Giver "+id+".");}}));}default->usageGiver(sender);}}
public void adventure(CommandSender sender,String[] args){
if(args.length==1){if(sender instanceof Player player)controller.inspect(player);else sender.sendMessage("Usage: /fstick adventure");return;}
if(args.length==2&&args[1].equals("tracking")){if(sender instanceof Player player)controller.tracking(player,null);else sender.sendMessage("Quest tracking requires a player.");return;}
if(args.length==3&&args[1].equals("tracking")&&(args[2].equals("on")||args[2].equals("off"))){if(sender instanceof Player player)controller.tracking(player,args[2].equals("on"));else sender.sendMessage("Quest tracking requires a player.");return;}
if(args.length==2&&args[1].equals("reroll")){
if(!authorized(sender))return;
if(adminAudit!=null){
var warning=adminAudit.current();
if(warning!=null){
if(rerollWarnings.size()>=256)rerollWarnings.clear();
rerollWarnings.put(sender,warning);
}
}
sender.sendMessage("Reroll expires every current adventure quest, encounter and reward claim. Run /fstickadmin adventure reroll confirm to reset the day.");
return;
}
if(args.length!=3||!args[1].equals("reroll")||!args[2].equals("confirm")){
sender.sendMessage("Usage: /fstick adventure [tracking [on|off]] or /fstickadmin adventure reroll [confirm]");
return;
}
var audit=adminAudit;
var confirmation=audit==null?null:audit.current();
var warning=rerollWarnings.remove(sender);
boolean permitted=sender.hasPermission(PERMISSION);
if(audit!=null)audit.confirmation(confirmation,permitted,"command_confirmation",warning==null?null:warning.id());
if(!authorized(sender)){
if(audit!=null)audit.result(warning==null?confirmation:warning,
games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"permission_changed",Map.of());
return;
}
var action=warning==null?confirmation:warning;
var current=directory.snapshot().catalog();
UUID expected=current==null?null:current.revision();
var campAudit=campEvents;
var actor=campAudit==null?null:campAudit.actor(sender,null);
directory.rerollToday(expected,actor).whenComplete((result,failure)->{
if(failure!=null){
if(audit!=null)audit.result(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED,"operation_failed",Map.of());
respond(sender,()->sender.sendMessage("Adventure reset failed; the current generation is unchanged."));
return;
}
if(result.status()==AdventureQuestDirectory.RerollStatus.STALE){
if(audit!=null)audit.result(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"stale",Map.of());
respond(sender,()->sender.sendMessage("Adventure reset refused: the generation changed or is still being published; inspect it and try again."));
return;
}
var catalog=result.catalog().orElseThrow();
// Capture the installed reset operation before native publication clears the pending proof.
var reset=directory.snapshot().reset();
UUID operation=reset!=null&&reset.generation().equals(catalog.revision())?reset.operation():null;
respond(sender,()->controller.publishPendingReset().whenComplete((published,publishFailure)->{
if(audit!=null){
var status=publishFailure==null&&Boolean.TRUE.equals(published)&&operation!=null
?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED
:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN;
audit.result(action,status,status==games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED
?"acknowledged":"operation_uncertain",
operation==null?Map.of():Map.of("domain_operation_id",operation));
}
respond(sender,()->{
if(publishFailure!=null||!Boolean.TRUE.equals(published)){sender.sendMessage("Adventure reset is saved but pending recovery; the new generation is not yet available.");return;}
sender.sendMessage("Reset daily adventures: generation="+catalog.revision()+", offers="+catalog.sites().size()+", expires="+catalog.expiresAt()+".");
});
}));
});
}
public void site(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){invalid();usageSite(sender);return;}switch(args[1]){case"list"->{if(args.length!=2){invalid();usageSite(sender);return;}var action=adminAudit==null?null:adminAudit.current();completedRead(action);if(directory.snapshot().sites().stream().noneMatch(v->v.type()!=AdventureQuestState.SiteType.DUNGEON))sender.sendMessage("No adventure sites registered.");else directory.snapshot().sites().stream().filter(v->v.type()!=AdventureQuestState.SiteType.DUNGEON).sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.type().name().toLowerCase(Locale.ROOT)+" "+v.displayName()+" at "+locations.format(v.world(),v.x(),v.y(),v.z())+"; "+controller.arena(v).display()+"; mode="+v.participationMode().value()+siteDetails(v)));}case"place"->{if(args.length<3||!(sender instanceof Player player)){if(args.length<3)invalid();else refused();usageSite(sender);return;}if(args[2].equals("fishing")){placeFishing(sender,player,args);return;}if(!(args[2].equals("camp")||args[2].equals("champion"))){invalid();usageSite(sender);return;}int start=3;var mode=AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;if(args.length>3&&args[3].equals("--mode")){if(args.length<5){invalid();usageSite(sender);return;}try{mode=AdventureQuestState.ParticipationMode.parse(args[4]);}catch(IllegalArgumentException invalid){invalid();usageSite(sender);return;}start=5;}var placement=placement(args,start);if(placement==null){invalid();usageSite(sender);return;}var location=player.getLocation();var type=args[2].equals("camp")?AdventureQuestState.SiteType.CAMP:AdventureQuestState.SiteType.CHAMPION;var action=adminAudit==null?null:adminAudit.current();var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,location);UUID operation=UUID.randomUUID();directory.placeSite(type,placement.name(),Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),placement.arena(),mode).whenComplete((value,failure)->{try{if(failure==null){if(campAudit!=null)campAudit.siteRegistered(operation,campActor,value,controller.arena(value));if(championEvents!=null)championEvents.siteRegistered(operation,campActor,value,controller.arena(value));}}catch(RuntimeException ignored){}saved(action,failure,failure==null,operation,failure==null?value.id():null);respond(sender,()->sender.sendMessage(failure==null?"Placed "+value.type().name().toLowerCase(Locale.ROOT)+" "+value.id()+" ("+value.displayName()+") at "+locations.format(value.world(),value.x(),value.y(),value.z())+"; "+controller.arena(value).display()+"; mode="+value.participationMode().value()+".":"Adventure site save failed; desired state is unchanged."));});}case"fishing"->{fishing(sender,args);}case"mode"->{if(args.length<3||args.length>4){invalid();usageSite(sender);return;}UUID id=parse(args[2]);var current=id==null?null:site(id).orElse(null);if(current==null){refused();sender.sendMessage("Adventure site not found.");return;}if(args.length==3){completedRead(adminAudit==null?null:adminAudit.current());sender.sendMessage("Adventure site "+id+" mode="+current.participationMode().value()+".");return;}AdventureQuestState.ParticipationMode requested;try{requested=AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){invalid();usageSite(sender);return;}var audit=fishingEvents;var auditActor=audit==null?null:audit.actor(sender);var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,null);var action=adminAudit==null?null:adminAudit.current();UUID operation=UUID.randomUUID();directory.setSiteMode(id,current.participationMode(),requested).whenComplete((result,failure)->{try{if(failure==null&&result.status()==AdventureQuestDirectory.ModeStatus.APPLIED){if(campAudit!=null)campAudit.siteModeChanged(operation,campActor,current,result.site().orElseThrow(),controller.arena(result.site().orElseThrow()));if(championEvents!=null)championEvents.siteModeChanged(operation,campActor,current,result.site().orElseThrow(),controller.arena(result.site().orElseThrow()));}}catch(RuntimeException ignored){}if(audit!=null&&current.type()==AdventureQuestState.SiteType.FISHING&&failure==null&&result.status()==AdventureQuestDirectory.ModeStatus.APPLIED)audit.site("adventure.site.mode_changed",operation,auditActor,result.site().orElseThrow(),Map.of("mode_before",current.participationMode().value(),"mode_after",requested.value()));if(failure!=null)saved(action,failure,false,null,null);else if(result.status()==AdventureQuestDirectory.ModeStatus.APPLIED)saved(action,null,true,operation,id);else outcome(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,result.status()==AdventureQuestDirectory.ModeStatus.STALE?"stale":result.status()==AdventureQuestDirectory.ModeStatus.UNCHANGED?"no_change":"not_found",null,null);respond(sender,()->{if(failure!=null){sender.sendMessage("AdvLine truncated
public void giver(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){invalid();usageGiver(sender);return;}switch(args[1]){case"list"->{if(args.length!=2){invalid();usageGiver(sender);return;}var action=adminAudit==null?null:adminAudit.current();completedRead(action);if(directory.snapshot().givers().isEmpty())sender.sendMessage("No Quest Givers registered.");else directory.snapshot().givers().stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.displayName()+" at "+locations.format(v.world(),v.x(),v.y(),v.z())));}case"place"->{if(!(sender instanceof Player player)){refused();usageGiver(sender);return;}String name=join(args,2);var location=player.getLocation();var action=adminAudit==null?null:adminAudit.current();var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,location);UUID operation=UUID.randomUUID();directory.placeGiver(name,Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch()).whenComplete((value,failure)->respond(sender,()->{if(failure!=null){saved(action,failure,false,null,null);sender.sendMessage("Quest Giver save failed; desired state is unchanged.");return;}var observed=controller.observedGiver(value);boolean nativeReturned=false;try{var world=plugin.getServer().getWorld(value.world());if(world!=null&&world.isChunkLoaded(section(value.x()),section(value.z())))controller.reconcile(world.getChunkAt(section(value.x()),section(value.z())));nativeReturned=true;}finally{auditGiver(campAudit,"adventure.quest_giver.placed",operation,campActor,value,observed,nativeReturned);}saved(action,null,true,operation,value.id());sender.sendMessage("Placed Quest Giver "+value.id()+" ("+value.displayName()+") at "+locations.format(value.world(),value.x(),value.y(),value.z())+".");}));}case"remove"->{if(args.length!=3){invalid();usageGiver(sender);return;}UUID id=parse(args[2]);if(id==null){invalid();usageGiver(sender);return;}var campAudit=campEvents;var campActor=campAudit==null?null:campAudit.actor(sender,null);var action=adminAudit==null?null:adminAudit.current();UUID operation=UUID.randomUUID();directory.removeGiver(id).whenComplete((removed,failure)->respond(sender,()->{if(failure!=null){saved(action,failure,false,null,null);sender.sendMessage("Quest Giver removal failed; desired state is unchanged.");}else if(removed.isEmpty()){outcome(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"not_found",null,null);sender.sendMessage("Quest Giver not found.");}else{var value=removed.orElseThrow();var observed=controller.observedGiver(value);boolean nativeReturned=false;try{controller.removeGiverLoaded(id);nativeReturned=true;}finally{auditGiver(campAudit,"adventure.quest_giver.removed",operation,campActor,value,observed,nativeReturned);}saved(action,null,true,operation,id);sender.sendMessage("Removed Quest Giver "+id+".");}}));}default->{invalid();usageGiver(sender);}}}
public List<String> complete(CommandSender sender,String[] args){if(args.length==1){var values=new ArrayList<String>();values.add("adventure");if(sender.hasPermission(PERMISSION)){values.add("adventure-site");values.add("quest-giver");}return matching(values,args[0]);}if(args.length==2&&args[0].equals("adventure")){var values=new ArrayList<String>();if(sender instanceof Player player&&controller.trackingAvailable(player))values.add("tracking");if(sender.hasPermission(PERMISSION))values.add("reroll");return matching(values,args[1]);}if(args.length==3&&args[0].equals("adventure")&&args[1].equals("tracking")&&sender instanceof Player player&&controller.trackingAvailable(player))return matching(List.of("on","off"),args[2]);if(!sender.hasPermission(PERMISSION))return List.of();if(args.length==3&&args[0].equals("adventure")&&args[1].equals("reroll"))return matching(List.of("confirm"),args[2]);if(args.length==2&&args[0].equals("adventure-site"))return matching(sender instanceof Player?List.of("fishing","list","mode","place","remove","teleport"):List.of("fishing","list","mode","remove"),args[1]);if(args.length==3&&args[0].equals("adventure-site")&&args[1].equals("place"))return matching(List.of("camp","champion","fishing"),args[2]);if(args.length>=4&&args[0].equals("adventure-site")&&args[1].equals("place")&&args[2].equals("fishing"))return fishingOptionCompletion(args);if(args.length==4&&args[0].equals("adventure-site")&&args[1].equals("place")&&(args[2].equals("camp")||args[2].equals("champion"))){var values=new ArrayList<>(List.of("--mode","4","16","64"));return matching(values,args[3]);}if(args.length==5&&args[0].equals("adventure-site")&&args[1].equals("place")&&args[3].equals("--mode"))return matching(modeValues(),args[4]);if(args.length==6&&args[0].equals("adventure-site")&&args[1].equals("place")&&args[3].equals("--mode"))return matching(List.of("4","16","64"),args[5]);if(args.length==5&&args[0].equals("adventure-site")&&args[1].equals("place")&&whole(args[3])!=null)return matching(List.of("8","16","128"),args[4]);if(args.length==7&&args[0].equals("adventure-site")&&args[1].equals("place")&&args[3].equals("--mode")&&whole(args[5])!=null)return matching(List.of("8","16","128"),args[6]);if(args.length==3&&args[0].equals("adventure-site")&&Set.of("fishing","mode","remove","teleport").contains(args[1]))return matching(directory.snapshot().sites().stream().filter(v->v.type()!=AdventureQuestState.SiteType.DUNGEON).map(v->v.id().toString()).toList(),args[2]);if(args.length==4&&args[0].equals("adventure-site")&&args[1].equals("mode"))return matching(modeValues(),args[3]);if(args.length>=4&&args[0].equals("adventure-site")&&args[1].equals("fishing"))return fishingOptionCompletion(args);if(args.length==2&&args[0].equals("quest-giver"))return matching(sender instanceof Player?List.of("list","place","remove"):List.of("list","remove"),args[1]);if(args.length==3&&args[0].equals("quest-giver")&&args[1].equals("remove"))return matching(directory.snapshot().givers().stream().map(v->v.id().toString()).toList(),args[2]);return List.of();}
private void placeFishing(CommandSender sender,Player player,String[] args){var options=options(args,3,Set.of("name","item","required","chance","xp","coins","radius","mode"));if(options==null||!options.keySet().containsAll(Set.of("name","item","required","chance","xp","coins"))){usageSite(sender);return;}try{int radius=options.containsKey("radius")?bounded(options.get("radius"),4,64):directory.defaultRadius();var mode=options.containsKey("mode")?AdventureQuestState.ParticipationMode.parse(options.get("mode")):AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;var location=player.getLocation();var audit=fishingEvents;var actor=audit==null?null:audit.actor(sender);directory.placeFishingSite(options.get("name"),options.get("item"),Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),radius,percent(options.get("chance")),positive(options.get("required")),nonnegative(options.get("xp")),nonnegative(options.get("coins")),mode).whenComplete((value,failure)->{if(failure==null&&audit!=null)audit.site("adventure.site.registered",value.id(),actor,value,Map.of("definition","created"));respond(sender,()->sender.sendMessage(failure==null?"Placed fishing site "+value.id()+" ("+value.displayName()+"); "+fishingDetails(value)+".":"Fishing site save failed; desired state is unchanged."));});}catch(IllegalArgumentException invalid){usageSite(sender);}}
private void fishing(CommandSender sender,String[] args){if(args.length<3){usageSite(sender);return;}UUID id=parse(args[2]);var current=id==null?null:directory.findSite(id).filter(value->value.type()==AdventureQuestState.SiteType.FISHING).orElse(null);if(current==null){sender.sendMessage("Fishing site not found.");return;}if(args.length==3){sender.sendMessage(current.id()+" "+current.displayName()+"; "+fishingDetails(current)+".");return;}var options=options(args,3,Set.of("name","item","required","chance","xp","coins","radius","mode"));if(options==null||options.isEmpty()){usageSite(sender);return;}try{var before=current.fishing();var definition=new AdventureQuestState.FishingDefinition(before.itemId(),options.getOrDefault("item",before.itemName()),options.containsKey("required")?positive(options.get("required")):before.required(),options.containsKey("chance")?percent(options.get("chance")):before.chancePercent(),options.containsKey("xp")?nonnegative(options.get("xp")):before.rewardXp(),options.containsKey("coins")?nonnegative(options.get("coins")):before.rewardCoins(),options.containsKey("radius")?bounded(options.get("radius"),4,64):before.radius());var mode=options.containsKey("mode")?AdventureQuestState.ParticipationMode.parse(options.get("mode")):current.participationMode();var audit=fishingEvents;var actor=audit==null?null:audit.actor(sender);directory.updateFishingSite(id,current,options.getOrDefault("name",current.name()),definition,mode).whenComplete((result,failure)->{if(failure==null&&result.status()==AdventureQuestDirectory.FishingUpdateStatus.APPLIED&&audit!=null){var changes=new LinkedHashMap<String,Object>();for(var field:options.keySet())changes.put(field,options.get(field));audit.site("adventure.site.updated",id,actor,result.site().orElseThrow(),changes);}respond(sender,()->{if(failure!=null){sender.sendMessage("Fishing site update failed; the acknowledged definition is unchanged.");return;}sender.sendMessage(switch(result.status()){case APPLIED->"Updated fishing site "+id+"; "+fishingDetails(result.site().orElseThrow())+".";case UNCHANGED->"Fishing site "+id+" is unchanged.";case STALE->"Fishing site update refused: the acknowledged definition changed; inspect and retry.";case NOT_FOUND->"Fishing site not found.";});});});}catch(IllegalArgumentException invalid){usageSite(sender);}}
private void placeFishing(CommandSender sender,Player player,String[] args){var options=options(args,3,Set.of("name","item","required","chance","xp","coins","radius","mode"));if(options==null||!options.keySet().containsAll(Set.of("name","item","required","chance","xp","coins"))){usageSite(sender);return;}try{int radius=options.containsKey("radius")?bounded(options.get("radius"),4,64):directory.defaultRadius();var mode=options.containsKey("mode")?AdventureQuestState.ParticipationMode.parse(options.get("mode")):AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;var location=player.getLocation();var action=adminAudit==null?null:adminAudit.current();var audit=fishingEvents;var actor=audit==null?null:audit.actor(sender);directory.placeFishingSite(options.get("name"),options.get("item"),Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),radius,percent(options.get("chance")),positive(options.get("required")),nonnegative(options.get("xp")),nonnegative(options.get("coins")),mode).whenComplete((value,failure)->{if(failure==null&&audit!=null)audit.site("adventure.site.registered",value.id(),actor,value,Map.of("definition","created"));saved(action,failure,failure==null,failure==null?value.id():null,failure==null?value.id():null);respond(sender,()->sender.sendMessage(failure==null?"Placed fishing site "+value.id()+" ("+value.displayName()+"); "+fishingDetails(value)+".":"Fishing site save failed; desired state is unchanged."));});}catch(IllegalArgumentException invalid){invalid();usageSite(sender);}}
private void fishing(CommandSender sender,String[] args){if(args.length<3){usageSite(sender);return;}UUID id=parse(args[2]);var current=id==null?null:directory.findSite(id).filter(value->value.type()==AdventureQuestState.SiteType.FISHING).orElse(null);if(current==null){refused();sender.sendMessage("Fishing site not found.");return;}if(args.length==3){completedRead(adminAudit==null?null:adminAudit.current());sender.sendMessage(current.id()+" "+current.displayName()+"; "+fishingDetails(current)+".");return;}var options=options(args,3,Set.of("name","item","required","chance","xp","coins","radius","mode"));if(options==null||options.isEmpty()){usageSite(sender);return;}try{var before=current.fishing();var definition=new AdventureQuestState.FishingDefinition(before.itemId(),options.getOrDefault("item",before.itemName()),options.containsKey("required")?positive(options.get("required")):before.required(),options.containsKey("chance")?percent(options.get("chance")):before.chancePercent(),options.containsKey("xp")?nonnegative(options.get("xp")):before.rewardXp(),options.containsKey("coins")?nonnegative(options.get("coins")):before.rewardCoins(),options.containsKey("radius")?bounded(options.get("radius"),4,64):before.radius());var mode=options.containsKey("mode")?AdventureQuestState.ParticipationMode.parse(options.get("mode")):current.participationMode();var action=adminAudit==null?null:adminAudit.current();var audit=fishingEvents;var actor=audit==null?null:audit.actor(sender);UUID operation=UUID.randomUUID();directory.updateFishingSite(id,current,options.getOrDefault("name",current.name()),definition,mode).whenComplete((result,failure)->{if(failure==null&&result.status()==AdventureQuestDirectory.FishingUpdateStatus.APPLIED&&audit!=null){var changes=new LinkedHashMap<String,Object>();for(var field:options.keySet())changes.put(field,options.get(field));audit.site("adventure.site.updated",operation,actor,result.site().orElseThrow(),changes);}if(failure!=null)saved(action,failure,false,null,null);else if(result.status()==AdventureQuestDirectory.FishingUpdateStatus.APPLIED)saved(action,null,true,operation,id);else outcome(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,result.status()==AdventureQuestDirectory.FishingUpdateStatus.STALE?"stale":result.status()==AdventureQuestDirectory.FishingUpdateStatus.UNCHANGED?"no_change":"not_found",null,null);respond(sender,()->{if(failure!=null){sender.sendMessage("Fishing site update failed; the acknowledged definition is unchanged.");return;}sender.sendMessage(switch(result.status()){case APPLIED->"Updated fishing site "+id+"; "+fishingDetails(result.site().orElseThrow())+".";case UNCHANGED->"Fishing site "+id+" is unchanged.";case STALE->"Fishing site update refused: the acknowledged definition changed; inspect and retry.";case NOT_FOUND->"Fishing site not found.";});});});}catch(IllegalArgumentException invalid){invalid();usageSite(sender);}}
private static String siteDetails(AdventureQuestState.Site site){return site.fishing()==null?"":"; "+fishingDetails(site);}
private static String fishingDetails(AdventureQuestState.Site site){var value=site.fishing();return "item=\""+value.itemName()+"\", required="+value.required()+", chance="+value.chancePercent().toPlainString()+"%, reward="+value.rewardXp()+" XP/"+value.rewardCoins()+" coins, radius="+value.radius()+", mode="+site.participationMode().value();}
private static Map<String,String> options(String[] args,int start,Set<String> allowed){var result=new LinkedHashMap<String,String>();for(int index=start;index<args.length;index++){String raw=args[index];if(!raw.startsWith("--")||!allowed.contains(raw.substring(2))||result.containsKey(raw.substring(2))||index+1>=args.length)return null;String key=raw.substring(2),value=args[++index];if(value.startsWith("\"")){var joined=new StringBuilder(value);while(!joined.toString().endsWith("\"")&&index+1<args.length)joined.append(' ').append(args[++index]);value=joined.toString();if(value.length()<2||!value.endsWith("\""))return null;value=value.substring(1,value.length()-1);}if(value.isBlank()||value.startsWith("--"))return null;result.put(key,value);}return result;}
@@ -34,7 +116,7 @@ public final class AdventureQuestCommands {
private static List<String> fishingOptionCompletion(String[] args){String current=args[args.length-1];if(args.length>=2){String previous=args[args.length-2];if(previous.equals("--mode"))return matching(modeValues(),current);if(previous.equals("--radius"))return matching(List.of("4","16","64"),current);if(previous.equals("--chance"))return matching(List.of("0","20","100"),current);if(previous.equals("--required"))return matching(List.of("1","5","2147483647"),current);if(previous.equals("--xp")||previous.equals("--coins"))return matching(List.of("0","10","100","2147483647"),current);}var used=Arrays.stream(args).filter(value->value.startsWith("--")).collect(java.util.stream.Collectors.toSet());return matching(List.of("--chance","--coins","--item","--mode","--name","--radius","--required","--xp").stream().filter(value->!used.contains(value)).toList(),current);}
private Optional<AdventureQuestState.Site> site(UUID id){return directory.findSite(id).filter(value->value.type()!=AdventureQuestState.SiteType.DUNGEON);}
private static AdventureAdminTeleport.Target target(AdventureQuestState.Site site){return new AdventureAdminTeleport.Target(site.id(),site.displayName(),switch(site.type()){case CAMP->"monster camp";case CHAMPION->"champion";case FISHING->"fishing site";case DUNGEON->"dungeon entrance";},site.world(),site.x(),site.y(),site.z(),0,0,true);}
private boolean authorized(CommandSender sender){if(sender.hasPermission(PERMISSION))return true;sender.sendMessage("Permission denied: you need fantasystick.admin to administer Fantasy Stick.");return false;}
private boolean authorized(CommandSender sender){if(sender.hasPermission(PERMISSION))return true;outcome(adminAudit==null?null:adminAudit.current(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"permission_changed",null,null);sender.sendMessage("Permission denied: you need fantasystick.admin to administer Fantasy Stick.");return false;}
private void auditGiver(games.dmg.fantasystick.events.CampEventBridge bridge,String type,UUID operation,
games.dmg.fantasystick.events.CampEventBridge.Actor actor,AdventureQuestState.Giver giver,
AdventureQuestController.ObservedGiver before,boolean nativeReturned){
@@ -41,7 +41,9 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
private games.dmg.fantasystick.events.ProgressionEventBridge progressionEvents;
private games.dmg.fantasystick.events.AbilityEventBridge abilityEvents;
private games.dmg.fantasystick.events.PassiveEventBridge passiveEvents;
private final Map<UUID, Object> adminPending = new ConcurrentHashMap<>();
private record AdminLoad(games.dmg.fantasystick.events.AdminActionEventBridge.Action action) { }
private final Map<UUID, AdminLoad> adminPending = new ConcurrentHashMap<>();
private games.dmg.fantasystick.events.AdminActionEventBridge adminAudit;
private final Map<UUID, AdminView> adminViews = new ConcurrentHashMap<>();
private final Map<UUID, SavedView> savedViews = new ConcurrentHashMap<>();
private volatile boolean closed;
@@ -123,6 +125,25 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
public void attachFishingInventory(games.dmg.fantasystick.adventure.FishingDirectory fishing){if(closed||this.fishing!=null)throw new IllegalStateException("Fishing inventory already attached or books closed");this.fishing=Objects.requireNonNull(fishing);}
public void attachRareInventory(games.dmg.fantasystick.shop.RareInventoryDirectory inventory,games.dmg.fantasystick.shop.RarePotionService potions,games.dmg.fantasystick.shop.RareReskillService reskills,games.dmg.fantasystick.shop.RareMagicCoreService magicCores){if(closed||rareInventory!=null)throw new IllegalStateException("Rare inventory already attached or books closed");rareInventory=Objects.requireNonNull(inventory);rarePotions=Objects.requireNonNull(potions);rareReskills=Objects.requireNonNull(reskills);rareMagicCores=Objects.requireNonNull(magicCores);}
public void attachAdminAudit(games.dmg.fantasystick.events.AdminActionEventBridge audit){if(closed||adminAudit!=null)throw new IllegalStateException("Admin audit already attached or controller closed");adminAudit=Objects.requireNonNull(audit);}
private games.dmg.fantasystick.events.AdminActionEventBridge.Action commandAction() {
return adminAudit == null ? null : adminAudit.current();
}
private void adminResult(games.dmg.fantasystick.events.AdminActionEventBridge.Action action,
games.dmg.fantasystick.events.AdminActionEventBridge.Outcome outcome,
String reason, UUID subject) {
if (action != null && adminAudit != null)
adminAudit.result(action, outcome, reason, subject == null ? Map.of() : Map.of("subject_id", subject));
}
private void supersedeAdminLoad(UUID administrator, AdminLoad load) {
var previous = adminPending.put(administrator, load);
if (previous != null) adminResult(previous.action(), games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain", null);
}
public void attachEvents(games.dmg.fantasystick.events.BookEventBridge events){if(closed||bookEvents!=null)throw new IllegalStateException("Book events already attached or controller closed");bookEvents=Objects.requireNonNull(events);}
public void attachProgressionEvents(games.dmg.fantasystick.events.ProgressionEventBridge events){if(closed||progressionEvents!=null)throw new IllegalStateException("Progression events already attached or controller closed");progressionEvents=Objects.requireNonNull(events);}
public void attachAbilityEvents(games.dmg.fantasystick.events.AbilityEventBridge events){if(closed||abilityEvents!=null)throw new IllegalStateException("Ability events already attached or controller closed");abilityEvents=Objects.requireNonNull(events);}
@@ -132,64 +153,76 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
public void openReadOnly(org.bukkit.entity.Player administrator, org.bukkit.entity.Player target) {
Objects.requireNonNull(administrator); Objects.requireNonNull(target);
if (closed) return;
var action = commandAction();
if (closed) { adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null); return; }
if (!administrator.isOnline() || !administrator.hasPermission("fantasystick.admin")) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "permission_changed", null);
if (administrator.isOnline()) administrator.sendMessage("Character view refused: administrator permission is required.");
return;
}
UUID targetId = target.getUniqueId();
var active = sessions.active(targetId).filter(sessions::current).orElse(null);
if (active == null) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "not_found", null);
administrator.sendMessage("Character view refused: the target has no current active character.");
return;
}
loadReadOnly(administrator, target, active, 0);
loadReadOnly(administrator, target, active, 0, action);
}
private void loadReadOnly(org.bukkit.entity.Player administrator, org.bukkit.entity.Player target,
games.dmg.fantasystick.session.EquipmentSessions.Active active, int offset) {
if (closed) return;
games.dmg.fantasystick.session.EquipmentSessions.Active active, int offset,
games.dmg.fantasystick.events.AdminActionEventBridge.Action action) {
if (closed) { adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null); return; }
UUID administratorId = administrator.getUniqueId();
UUID targetId = target.getUniqueId();
Object ticket = new Object();
var load = new AdminLoad(action);
adminViews.remove(administratorId);
savedViews.remove(administratorId);
adminPending.put(administratorId, ticket);
supersedeAdminLoad(administratorId, load);
characters.find(active.character()).whenComplete((record, failure) -> {
if (closed || adminPending.get(administratorId) != ticket) return;
if (closed || adminPending.get(administratorId) != load) return;
try {
nextTick.accept(() -> {
if (closed || !adminPending.remove(administratorId, ticket)) return;
if (closed || !adminPending.remove(administratorId, load)) return;
var currentTarget = server.getPlayer(targetId);
var current = currentTarget == null ? null : sessions.active(targetId)
.filter(sessions::current).orElse(null);
if (!administrator.isOnline() || !administrator.hasPermission("fantasystick.admin")) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "permission_changed", null);
if (administrator.isOnline()) administrator.sendMessage("Character view refused: administrator permission changed.");
return;
}
if (currentTarget != target || !target.isOnline() || !active.equals(current)) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "stale", null);
administrator.sendMessage("Character view refused: the target character session changed.");
return;
}
if (failure != null) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
report(new Failure(administratorId, active.character(), failure));
administrator.sendMessage("Character view could not be loaded; no state was changed.");
return;
}
if (record.isEmpty() || record.orElseThrow().dead()) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "not_found", null);
administrator.sendMessage("Character view refused: the target character is unavailable.");
return;
}
try { administrator.openBook(renderReadOnly(record.orElseThrow(), administrator,
currentTarget, active, offset)); }
catch (RuntimeException error) {
try {
administrator.openBook(renderReadOnly(record.orElseThrow(), administrator, currentTarget, active, offset));
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,
"read_completed", active.character());
} catch (RuntimeException error) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
adminViews.remove(administratorId);
report(new Failure(administratorId, active.character(), error));
administrator.sendMessage("Character view could not be opened; no state was changed.");
}
});
} catch (RuntimeException rejected) {
adminPending.remove(administratorId, ticket);
if (adminPending.remove(administratorId, load))
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
report(new Failure(administratorId, active.character(), rejected));
}
});
@@ -197,48 +230,59 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
public void openSavedReadOnly(org.bukkit.entity.Player administrator, UUID character) {
Objects.requireNonNull(administrator); Objects.requireNonNull(character);
if (closed) return;
var action = commandAction();
if (closed) { adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null); return; }
if (!administrator.isOnline() || !administrator.hasPermission("fantasystick.admin")) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "permission_changed", null);
if (administrator.isOnline()) administrator.sendMessage("Saved character view refused: administrator permission is required.");
return;
}
loadSavedReadOnly(administrator, character, 0);
loadSavedReadOnly(administrator, character, 0, action);
}
private void loadSavedReadOnly(org.bukkit.entity.Player administrator, UUID character, int offset) {
if (closed) return;
private void loadSavedReadOnly(org.bukkit.entity.Player administrator, UUID character, int offset,
games.dmg.fantasystick.events.AdminActionEventBridge.Action action) {
if (closed) { adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null); return; }
UUID administratorId = administrator.getUniqueId();
Object ticket = new Object();
var load = new AdminLoad(action);
adminViews.remove(administratorId);
savedViews.remove(administratorId);
adminPending.put(administratorId, ticket);
supersedeAdminLoad(administratorId, load);
characters.inspect(character).whenComplete((record, failure) -> {
if (closed || adminPending.get(administratorId) != ticket) return;
if (closed || adminPending.get(administratorId) != load) return;
try {
nextTick.accept(() -> {
if (closed || !adminPending.remove(administratorId, ticket)) return;
if (closed || !adminPending.remove(administratorId, load)) return;
if (!administrator.isOnline() || !administrator.hasPermission("fantasystick.admin")) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "permission_changed", null);
if (administrator.isOnline()) administrator.sendMessage("Saved character view refused: administrator permission changed.");
return;
}
if (failure != null) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
report(new Failure(administratorId, character, failure));
administrator.sendMessage("Saved character view could not be loaded; no state was changed.");
return;
}
if (record.isEmpty()) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "not_found", null);
administrator.sendMessage("Saved character view refused: character not found.");
return;
}
try { administrator.openBook(renderSavedReadOnly(record.orElseThrow(), administrator, offset)); }
catch (RuntimeException error) {
try {
administrator.openBook(renderSavedReadOnly(record.orElseThrow(), administrator, offset));
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,
"read_completed", character);
} catch (RuntimeException error) {
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
savedViews.remove(administratorId);
report(new Failure(administratorId, character, error));
administrator.sendMessage("Saved character view could not be opened; no state was changed.");
}
});
} catch (RuntimeException rejected) {
adminPending.remove(administratorId, ticket);
if (adminPending.remove(administratorId, load))
adminResult(action, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed", null);
report(new Failure(administratorId, character, rejected));
}
});
@@ -748,7 +792,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
if (!match.matches() || !view.nonce().equals(match.group(1))) return;
int offset = match.group(2).equals("0") ? view.previous() : view.next();
if (offset < 0 || !savedViews.remove(administrator.getUniqueId(), view)) return;
loadSavedReadOnly(administrator, view.character(), offset);
loadSavedReadOnly(administrator, view.character(), offset, null);
}
@org.bukkit.event.EventHandler
@@ -764,7 +808,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
if (!match.matches() || !view.nonce().equals(match.group(1))) return;
int offset = match.group(2).equals("0") ? view.previous() : view.next();
if (offset < 0 || !adminViews.remove(administrator.getUniqueId(), view)) return;
loadReadOnly(administrator, view.target(), view.active(), offset);
loadReadOnly(administrator, view.target(), view.active(), offset, null);
}
@org.bukkit.event.EventHandler
@@ -971,7 +1015,9 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
var owner = event.getPlayer().getUniqueId();
pending.remove(owner);
var bookRequest=pendingBookEvents.remove(owner);if(bookRequest!=null)bookEvents.refused(bookRequest,"player_quit");
adminPending.remove(owner);
var adminLoad = adminPending.remove(owner);
if (adminLoad != null) adminResult(adminLoad.action(),
games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null);
adminViews.remove(owner);
savedViews.remove(owner);
views.remove(owner);
@@ -984,6 +1030,6 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
}
@Override public void close() {
closed = true; pending.clear();pendingBookEvents.values().forEach(request->bookEvents.refused(request,"plugin_shutdown"));pendingBookEvents.clear(); adminPending.clear(); adminViews.clear(); savedViews.clear(); views.clear(); statViews.clear(); abilityViews.clear(); passiveViews.clear(); rareViews.clear(); reskillViews.clear(); partyControls.close();
closed = true; pending.clear();pendingBookEvents.values().forEach(request->bookEvents.refused(request,"plugin_shutdown"));pendingBookEvents.clear(); adminPending.values().forEach(load -> adminResult(load.action(), games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", null)); adminPending.clear(); adminViews.clear(); savedViews.clear(); views.clear(); statViews.clear(); abilityViews.clear(); passiveViews.clear(); rareViews.clear(); reskillViews.clear(); partyControls.close();
}
}
@@ -20,42 +20,92 @@ public final class DungeonCommands {
private final Plugin plugin;private final DungeonDirectory directory;private final DungeonController controller;private final games.dmg.fantasystick.adventure.AdventureQuestDirectory adventures;private final Consumer<Runnable> nextTick;private final games.dmg.fantasystick.adventure.AdventureLocationPresentation locations;private final Function<UUID,CompletableFuture<Optional<CharacterRecord>>> characters;private final Predicate<UUID> activeCharacter;private final Predicate<UUID> partyCharacter;private final CharacterSheets sheets=new CharacterSheets();private final AdventureAdminTeleport teleports;private games.dmg.fantasystick.events.DungeonEventBridge auditEvents;private games.dmg.fantasystick.events.DungeonAuditEventBridge ownerEvents;private games.dmg.fantasystick.events.CharacterBossEventBridge characterBossEvents;
public DungeonCommands(Plugin plugin,DungeonDirectory directory,DungeonController controller,games.dmg.fantasystick.adventure.AdventureQuestDirectory adventures,Consumer<Runnable> nextTick){this(plugin,directory,controller,adventures,nextTick,id->CompletableFuture.completedFuture(Optional.empty()),id->false,id->false);}
public DungeonCommands(Plugin plugin,DungeonDirectory directory,DungeonController controller,games.dmg.fantasystick.adventure.AdventureQuestDirectory adventures,Consumer<Runnable> nextTick,Function<UUID,CompletableFuture<Optional<CharacterRecord>>> characters,Predicate<UUID> activeCharacter,Predicate<UUID> partyCharacter){this.plugin=Objects.requireNonNull(plugin);this.directory=Objects.requireNonNull(directory);this.controller=Objects.requireNonNull(controller);this.adventures=Objects.requireNonNull(adventures);this.nextTick=Objects.requireNonNull(nextTick);this.characters=Objects.requireNonNull(characters);this.activeCharacter=Objects.requireNonNull(activeCharacter);this.partyCharacter=Objects.requireNonNull(partyCharacter);locations=new games.dmg.fantasystick.adventure.AdventureLocationPresentation(plugin.getServer());teleports=new AdventureAdminTeleport(plugin,nextTick);}
private games.dmg.fantasystick.events.AdminActionEventBridge adminAudit;
public void attachAdminAudit(games.dmg.fantasystick.events.AdminActionEventBridge bridge){adminAudit=Objects.requireNonNull(bridge);}
private void completedRead(games.dmg.fantasystick.events.AdminActionEventBridge.Action action){adminResult(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"read_completed",null,null);}
private void adminResult(games.dmg.fantasystick.events.AdminActionEventBridge.Action action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome outcome,String reason,UUID operation,String type){
if(adminAudit==null||action==null)return;
Map<String,Object> facts=operation==null?Map.of():type==null?Map.of("domain_operation_id",operation):Map.of("domain_operation_id",operation,"domain_event_id",games.dmg.fantasystick.events.DungeonAuditEventBridge.eventId(operation,type));
adminAudit.result(action,outcome,reason,facts);
}
private void bossResult(games.dmg.fantasystick.events.AdminActionEventBridge.Action action,UUID operation,String type){if(adminAudit!=null&&action!=null)adminAudit.result(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",Map.of("domain_operation_id",operation,"domain_event_id",UUID.nameUUIDFromBytes(("fantasystick:character-boss:"+operation+":"+type).getBytes(java.nio.charset.StandardCharsets.UTF_8))));}
private void refused(String reason){adminResult(adminAudit==null?null:adminAudit.current(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,reason,null,null);}
private void confirm(){if(adminAudit!=null)adminAudit.confirmation(adminAudit.current(),true,"command_confirmation",null);}
private void savedResult(games.dmg.fantasystick.events.AdminActionEventBridge.Action action,Throwable failure,UUID operation,String type){
Throwable cause=failure;
while((cause instanceof java.util.concurrent.CompletionException||cause instanceof java.util.concurrent.ExecutionException)&&cause.getCause()!=null)cause=cause.getCause();
boolean validationRefused=cause instanceof IllegalArgumentException;
adminResult(action,failure==null?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED:validationRefused?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED,failure==null?"acknowledged":validationRefused?"owner_refused":"operation_failed",failure==null?operation:null,failure==null?type:null);
}
public void attachEvents(games.dmg.fantasystick.events.DungeonEventBridge events){this.auditEvents=Objects.requireNonNull(events);}
public void attachOwnerEvents(games.dmg.fantasystick.events.DungeonAuditEventBridge events){this.ownerEvents=Objects.requireNonNull(events);}
public void attachCharacterBossEvents(games.dmg.fantasystick.events.CharacterBossEventBridge events){this.characterBossEvents=Objects.requireNonNull(events);}
public void execute(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){usage(sender);return;}try{switch(args[1]){case"create"->create(sender,args);case"list"->list(sender,args);case"mode"->mode(sender,args);case"remove"->remove(sender,args);case"edit"->edit(sender,args);case"entrance"->entrance(sender,args);case"room"->room(sender,args);case"reward"->reward(sender,args);case"boss"->bossCommand(sender,args);case"teleport"->teleport(sender,args);case"enable"->enable(sender,args);case"disable"->disable(sender,args);case"open"->open(sender,args);case"close"->close(sender,args);default->usage(sender);}}catch(IllegalArgumentException invalid){sender.sendMessage("Dungeon command refused: "+invalid.getMessage()+".");}}
private void create(CommandSender sender,String[] args){if(args.length<3||!(sender instanceof Player player)){usage(sender);return;}int nameStart=2;var mode=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;if(args[2].equals("--mode")){if(args.length<5){usage(sender);return;}try{mode=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){usage(sender);return;}nameStart=4;}else if(args[2].startsWith("--")){usage(sender);return;}String name=join(args,nameStart);if(name.isBlank()){usage(sender);return;}var location=player.getLocation();var audit=ownerEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();directory.create(name,Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch(),mode).whenComplete((value,failure)->{if(failure==null&&audit!=null)try{audit.created(operation,actor,value);}catch(RuntimeException ignored){/* Audit cannot undo acknowledged authoring. */}respond(sender,()->sender.sendMessage(failure==null?"Created disabled dungeon "+value.id()+" ("+value.name()+"); mode="+value.participationMode().value()+".":"Dungeon creation failed; desired state is unchanged."));});}
private void list(CommandSender sender,String[] args){if(args.length!=2){usage(sender);return;}if(directory.snapshot().dungeons().isEmpty()){sender.sendMessage("No dungeons registered.");return;}directory.snapshot().dungeons().stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(value->sender.sendMessage(value.id()+" "+value.name()+" at "+locations.format(value.world(),value.entrance().x(),value.entrance().y(),value.entrance().z())+"; "+(value.enabled()?"enabled":"disabled")+"; mode="+value.participationMode().value()+"; rooms="+value.rooms().size()+"; completion="+(value.rewardConfigured()?value.completionReward().xp()+" XP, "+value.completionReward().coins()+" coins":"not configured")+"."));}
private void mode(CommandSender sender,String[] args){if(args.length<3||args.length>4){usage(sender);return;}UUID id=id(args[2]);var current=id==null?null:directory.find(id).orElse(null);if(current==null){sender.sendMessage("Dungeon not found.");return;}if(args.length==3){sender.sendMessage("Dungeon "+id+" mode="+current.participationMode().value()+".");return;}games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode requested;try{requested=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){usage(sender);return;}var audit=ownerEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();directory.setModeWithEvidence(id,current.revision(),requested).whenComplete((change,failure)->{if(failure==null&&audit!=null)try{audit.modeChanged(operation,actor,change.before(),change.after());}catch(RuntimeException ignored){/* Audit cannot undo acknowledged authoring. */}respond(sender,()->sender.sendMessage(failure==null?"Updated dungeon "+id+" mode="+change.after().participationMode().value()+" for future acceptances.":"Dungeon mode update refused; the acknowledged definition is unchanged or stale."));});}
private void remove(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}if(directory.custodyForDungeon(id).isPresent()){sender.sendMessage("Recover character boss custody before removing this dungeon.");return;}var request=request(sender);controller.closeOffer(id).thenCompose(ignored->adventures.removeDungeonSite(id)).thenCompose(ignored->observedSave(request,"administrator_remove",()->directory.remove(id))).whenComplete((removed,failure)->respond(sender,()->sender.sendMessage(failure!=null?"Dungeon removal failed; desired state is retained.":removed.isPresent()?"Removed dungeon "+id+".":"Dungeon not found.")));}
private void edit(CommandSender sender,String[] args){if(!(sender instanceof Player player)){usage(sender);return;}if(args.length==3&&args[2].equals("done")){var request=request(sender);var before=controller.editing(player.getUniqueId()).flatMap(directory::find).orElse(null);boolean ended=controller.done(player.getUniqueId());if(ended&&before!=null&&request.events()!=null)try{request.events().lease("dungeon.edit.ended",request.operation(),request.actor(),before,"administrator_done");}catch(RuntimeException ignored){}sender.sendMessage(ended?"Dungeon editing ended; the dungeon remains disabled.":"No dungeon is being edited.");return;}if(args.length<4||args.length>5||!args[2].equals("start")||args.length==5&&!args[4].equals("confirm")){usage(sender);return;}UUID id=id(args[3]);if(id==null){usage(sender);return;}var request=request(sender);controller.startWithEvidence(player,id,args.length==5).whenComplete((publication,failure)->{var status=publication==null?null:publication.status();if(failure==null&&status==DungeonController.EditStatus.STARTED&&request.events()!=null)try{request.events().lease("dungeon.edit.started",request.operation(),request.actor(),publication.dungeon(),"administrator_start");}catch(RuntimeException ignored){}respond(sender,()->{if(failure!=null){plugin.getLogger().log(java.util.logging.Level.WARNING,"Dungeon edit transition failed",failure);sender.sendMessage("Dungeon edit transition failed; retained state is authoritative.");return;}sender.sendMessage(switch(status){case STARTED->"Editing dungeon "+id+"; it is disabled.";case CONFIRM_REQUIRED->"Dungeon has offered, accepted or progressed work; repeat with exact confirm to close and expire it.";case BUSY->"Dungeon editing refused: the editor or dungeon already has an editing lease.";case NOT_FOUND->"Dungeon not found.";});});});}
private void entrance(CommandSender sender,String[] args){if(args.length!=3||!args[2].equals("set")||!(sender instanceof Player player)){usage(sender);return;}UUID dungeon=editing(player);if(dungeon==null)return;var location=player.getLocation();if(location.getWorld()==null||!directory.find(dungeon).orElseThrow().world().equals(location.getWorld().getUID())){sender.sendMessage("Dungeon entrance must remain in its world.");return;}observedSave(sender,"administrator_entrance",()->directory.setEntrance(dungeon,location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Updated dungeon entrance."));}
private void room(CommandSender sender,String[] args){if(!(sender instanceof Player player)||args.length<3){usage(sender);return;}UUID dungeon=editing(player);if(dungeon==null)return;switch(args[2]){case"create"->roomCreate(sender,player,dungeon,args);case"list"->{if(args.length!=3){usage(sender);return;}var value=directory.find(dungeon).orElseThrow();if(value.rooms().isEmpty())sender.sendMessage("No rooms defined.");else value.rooms().stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.displayName()+" "+v.bounds()+"; mobs="+v.mobs().size()+"; effects="+v.effects().size()+"; boss="+(v.boss()==null?"none":v.boss().type().name().toLowerCase(Locale.ROOT))));}case"remove"->{if(args.length!=4){usage(sender);return;}UUID room=id(args[3]);if(room==null){usage(sender);return;}observedSave(sender,"administrator_room_remove",()->directory.removeRoom(dungeon,room)).whenComplete((value,failure)->{if(failure==null&&value.isPresent())controller.definitionChanged(dungeon);respond(sender,()->sender.sendMessage(failure!=null?"Room removal refused: it would overlap, disconnect or could not be saved.":value.isPresent()?"Removed room "+room+".":"Room not found."));});}case"mob"->mob(sender,player,dungeon,args);case"effect"->effect(sender,player,dungeon,args);case"boss"->boss(sender,player,dungeon,args);default->usage(sender);}}
public void execute(CommandSender sender,String[] args){if(!authorized(sender))return;if(args.length<2){usage(sender);return;}try{switch(args[1]){case"create"->create(sender,args);case"list"->list(sender,args);case"mode"->mode(sender,args);case"remove"->remove(sender,args);case"edit"->edit(sender,args);case"entrance"->entrance(sender,args);case"room"->room(sender,args);case"reward"->reward(sender,args);case"boss"->bossCommand(sender,args);case"teleport"->teleport(sender,args);case"enable"->enable(sender,args);case"disable"->disable(sender,args);case"open"->open(sender,args);case"close"->close(sender,args);default->usage(sender);}}catch(IllegalArgumentException invalid){refused("owner_refused");sender.sendMessage("Dungeon command refused: "+invalid.getMessage()+".");}}
private void create(CommandSender sender,String[] args){if(args.length<3||!(sender instanceof Player player)){if(!(sender instanceof Player))refused("sender_unsupported");usage(sender);return;}int nameStart=2;var mode=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.PARTY_AVAILABLE;if(args[2].equals("--mode")){if(args.length<5){usage(sender);return;}try{mode=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){usage(sender);return;}nameStart=4;}else if(args[2].startsWith("--")){usage(sender);return;}String name=join(args,nameStart);if(name.isBlank()){usage(sender);return;}var location=player.getLocation();var audit=ownerEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();var action=adminAudit==null?null:adminAudit.current();directory.create(name,Objects.requireNonNull(location.getWorld()).getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch(),mode).whenComplete((value,failure)->{if(failure==null&&audit!=null)try{audit.created(operation,actor,value);}catch(RuntimeException ignored){/* Audit cannot undo acknowledged authoring. */}savedResult(action,failure,operation,"dungeon.created");respond(sender,()->sender.sendMessage(failure==null?"Created disabled dungeon "+value.id()+" ("+value.name()+"); mode="+value.participationMode().value()+".":"Dungeon creation failed; desired state is unchanged."));});}
private void list(CommandSender sender,String[] args){if(args.length!=2){usage(sender);return;}var action=adminAudit==null?null:adminAudit.current();var dungeons=directory.snapshot().dungeons();if(dungeons.isEmpty()){sender.sendMessage("No dungeons registered.");completedRead(action);return;}dungeons.stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(value->sender.sendMessage(value.id()+" "+value.name()+" at "+locations.format(value.world(),value.entrance().x(),value.entrance().y(),value.entrance().z())+"; "+(value.enabled()?"enabled":"disabled")+"; mode="+value.participationMode().value()+"; rooms="+value.rooms().size()+"; completion="+(value.rewardConfigured()?value.completionReward().xp()+" XP, "+value.completionReward().coins()+" coins":"not configured")+"."));completedRead(action);}
private void mode(CommandSender sender,String[] args){if(args.length<3||args.length>4){usage(sender);return;}UUID id=id(args[2]);var current=id==null?null:directory.find(id).orElse(null);if(current==null){refused("not_found");sender.sendMessage("Dungeon not found.");return;}if(args.length==3){sender.sendMessage("Dungeon "+id+" mode="+current.participationMode().value()+".");completedRead(adminAudit==null?null:adminAudit.current());return;}games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode requested;try{requested=games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.parse(args[3]);}catch(IllegalArgumentException invalid){usage(sender);return;}var audit=ownerEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();var action=adminAudit==null?null:adminAudit.current();directory.setModeWithEvidence(id,current.revision(),requested).whenComplete((change,failure)->{if(failure==null&&audit!=null)try{audit.modeChanged(operation,actor,change.before(),change.after());}catch(RuntimeException ignored){/* Audit cannot undo acknowledged authoring. */}if(failure!=null){Throwable cause=failure;while(cause instanceof java.util.concurrent.CompletionException&&cause.getCause()!=null)cause=cause.getCause();adminResult(action,cause instanceof java.io.IOException?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,cause instanceof java.io.IOException?"operation_failed":"stale",null,null);}else if(change.before().equals(change.after()))refusedSave(action);else savedResult(action,null,operation,"dungeon.mode_changed");respond(sender,()->sender.sendMessage(failure==null?"Updated dungeon "+id+" mode="+change.after().participationMode().value()+" for future acceptances.":"Dungeon mode update refused; the acknowledged definition is unchanged or stale."));});}
private void remove(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}if(directory.custodyForDungeon(id).isPresent()){refused("owner_refused");sender.sendMessage("Recover character boss custody before removing this dungeon.");return;}confirm();var request=request(sender);controller.closeOffer(id).thenCompose(ignored->adventures.removeDungeonSite(id)).thenCompose(ignored->observedSave(request,"administrator_remove",()->directory.remove(id))).whenComplete((removed,failure)->respond(sender,()->sender.sendMessage(failure!=null?"Dungeon removal failed; desired state is retained.":removed.isPresent()?"Removed dungeon "+id+".":"Dungeon not found.")));}
private void edit(CommandSender sender,String[] args){if(!(sender instanceof Player player)){refused("sender_unsupported");usage(sender);return;}if(args.length==3&&args[2].equals("done")){var request=request(sender);var before=controller.editing(player.getUniqueId()).flatMap(directory::find).orElse(null);boolean ended=controller.done(player.getUniqueId());if(ended&&before!=null&&request.events()!=null)try{request.events().lease("dungeon.edit.ended",request.operation(),request.actor(),before,"administrator_done");}catch(RuntimeException ignored){}if(ended&&before!=null)savedResult(request.action(),null,request.operation(),"dungeon.edit.ended");else refused("no_change");sender.sendMessage(ended?"Dungeon editing ended; the dungeon remains disabled.":"No dungeon is being edited.");return;}if(args.length<4||args.length>5||!args[2].equals("start")||args.length==5&&!args[4].equals("confirm")){usage(sender);return;}UUID id=id(args[3]);if(id==null){usage(sender);return;}if(args.length==5)confirm();var request=request(sender);controller.startWithEvidence(player,id,args.length==5).whenComplete((publication,failure)->{var status=publication==null?null:publication.status();if(failure==null&&status==DungeonController.EditStatus.STARTED&&request.events()!=null)try{request.events().lease("dungeon.edit.started",request.operation(),request.actor(),publication.dungeon(),"administrator_start");}catch(RuntimeException ignored){}if(failure!=null)savedResult(request.action(),failure,null,null);else if(status==DungeonController.EditStatus.STARTED)savedResult(request.action(),null,request.operation(),"dungeon.edit.started");else adminResult(request.action(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,status==DungeonController.EditStatus.NOT_FOUND?"not_found":status==DungeonController.EditStatus.CONFIRM_REQUIRED?"confirmation_required":"owner_refused",null,null);respond(sender,()->{if(failure!=null){plugin.getLogger().log(java.util.logging.Level.WARNING,"Dungeon edit transition failed",failure);sender.sendMessage("Dungeon edit transition failed; retained state is authoritative.");return;}sender.sendMessage(switch(status){case STARTED->"Editing dungeon "+id+"; it is disabled.";case CONFIRM_REQUIRED->"Dungeon has offered, accepted or progressed work; repeat with exact confirm to close and expire it.";case BUSY->"Dungeon editing refused: the editor or dungeon already has an editing lease.";case NOT_FOUND->"Dungeon not found.";});});});}
private void entrance(CommandSender sender,String[] args){if(args.length!=3||!args[2].equals("set")||!(sender instanceof Player player)){usage(sender);return;}UUID dungeon=editing(player);if(dungeon==null)return;var location=player.getLocation();if(location.getWorld()==null||!directory.find(dungeon).orElseThrow().world().equals(location.getWorld().getUID())){refused("owner_refused");sender.sendMessage("Dungeon entrance must remain in its world.");return;}observedSave(sender,"administrator_entrance",()->directory.setEntrance(dungeon,location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Updated dungeon entrance."));}
private void room(CommandSender sender,String[] args){if(!(sender instanceof Player player)||args.length<3){if(!(sender instanceof Player))refused("sender_unsupported");usage(sender);return;}UUID dungeon=editing(player);if(dungeon==null)return;switch(args[2]){case"create"->roomCreate(sender,player,dungeon,args);case"list"->{if(args.length!=3){usage(sender);return;}var value=directory.find(dungeon).orElseThrow();if(value.rooms().isEmpty())sender.sendMessage("No rooms defined.");else value.rooms().stream().sorted(Comparator.comparing(v->v.id().toString())).forEach(v->sender.sendMessage(v.id()+" "+v.displayName()+" "+v.bounds()+"; mobs="+v.mobs().size()+"; effects="+v.effects().size()+"; boss="+(v.boss()==null?"none":v.boss().type().name().toLowerCase(Locale.ROOT))));completedRead(adminAudit==null?null:adminAudit.current());}case"remove"->{if(args.length!=4){usage(sender);return;}UUID room=id(args[3]);if(room==null){usage(sender);return;}observedSave(sender,"administrator_room_remove",()->directory.removeRoom(dungeon,room)).whenComplete((value,failure)->{if(failure==null&&value.isPresent())controller.definitionChanged(dungeon);respond(sender,()->sender.sendMessage(failure!=null?"Room removal refused: it would overlap, disconnect or could not be saved.":value.isPresent()?"Removed room "+room+".":"Room not found."));});}case"mob"->mob(sender,player,dungeon,args);case"effect"->effect(sender,player,dungeon,args);case"boss"->boss(sender,player,dungeon,args);default->usage(sender);}}
private void roomCreate(CommandSender sender,Player player,UUID dungeon,String[] args){if(args.length<6){usage(sender);return;}var location=player.getLocation();int x=location.getBlockX(),y=location.getBlockY()-1,z=location.getBlockZ();if(args[3].equals("corner")){if(args.length<7){usage(sender);return;}Integer xs=integer(args[4]),zs=integer(args[5]),height=integer(args[6]);if(xs==null||zs==null||height==null){usage(sender);return;}observedSave(sender,"administrator_room_create",()->directory.addCornerRoom(dungeon,join(args,7),x,y,z,xs,zs,height)).whenComplete((value,failure)->roomSaved(sender,dungeon,value,failure));return;}if(args[3].equals("radius")){Integer radius=integer(args[4]),height=integer(args[5]);if(radius==null||height==null){usage(sender);return;}observedSave(sender,"administrator_room_create",()->directory.addRadiusRoom(dungeon,join(args,6),x,y,z,radius,height)).whenComplete((value,failure)->roomSaved(sender,dungeon,value,failure));return;}usage(sender);}
private void roomSaved(CommandSender sender,UUID dungeon,DungeonState.Room value,Throwable failure){if(failure==null)controller.definitionChanged(dungeon);String message=failure==null?"Created room "+value.id()+" ("+value.displayName()+").":roomFailure(failure);respond(sender,()->sender.sendMessage(message));}
private static String roomFailure(Throwable failure){Throwable cause=failure;while((cause instanceof java.util.concurrent.CompletionException||cause instanceof java.util.concurrent.ExecutionException)&&cause.getCause()!=null)cause=cause.getCause();String detail=cause.getMessage();if(cause instanceof IllegalArgumentException&&"Rooms overlap".equals(detail))return "Room creation refused: it overlaps an existing room.";if(cause instanceof IllegalArgumentException&&detail!=null&&detail.startsWith("Room exceeds configured link distance of ")){String blocks=detail.substring("Room exceeds configured link distance of ".length()).replace(" blocks","");return "Room creation refused: nearest room is farther than the configured "+blocks+"-block link distance.";}if(cause instanceof IllegalArgumentException&&(detail!=null&&(detail.equals("Room dimensions out of range")||detail.equals("Room limit reached"))))return "Room creation refused: dimensions or room limit are out of range.";if(cause instanceof java.io.IOException)return "Room creation failed: persistence is unavailable; desired state is unchanged.";return "Room creation refused: geometry validation failed; desired state is unchanged.";}
private void mob(CommandSender sender,Player player,UUID dungeon,String[] args){var room=standing(sender,player);if(room==null)return;if(args.length>=5&&args[3].equals("add")){var type=entity(args[4]);if(!ordinary(type)){sender.sendMessage("Unsupported living mob type.");return;}var location=player.getLocation();observedSave(sender,"administrator_mob_add",()->directory.addMob(dungeon,room.id(),type,join(args,5),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Added mob slot "+(value==null?"":value.id())+"."));return;}if(args.length==5&&args[3].equals("remove")){UUID id=id(args[4]);if(id==null){usage(sender);return;}observedSave(sender,"administrator_mob_remove",()->directory.removeMob(dungeon,room.id(),id)).whenComplete((value,failure)->saved(sender,failure,value!=null&&value.isPresent()?"Removed mob slot "+id+".":"Mob slot not found."));return;}if(args.length==4&&args[3].equals("list")){if(room.mobs().isEmpty())sender.sendMessage("No ordinary mob slots in this room.");else room.mobs().forEach(value->sender.sendMessage(value.id()+" "+value.type().name().toLowerCase(Locale.ROOT)+" "+value.name()));return;}usage(sender);}
private void mob(CommandSender sender,Player player,UUID dungeon,String[] args){var room=standing(sender,player);if(room==null)return;if(args.length>=5&&args[3].equals("add")){var type=entity(args[4]);if(!ordinary(type)){refused("owner_refused");sender.sendMessage("Unsupported living mob type.");return;}var location=player.getLocation();observedSave(sender,"administrator_mob_add",()->directory.addMob(dungeon,room.id(),type,join(args,5),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Added mob slot "+(value==null?"":value.id())+"."));return;}if(args.length==5&&args[3].equals("remove")){UUID id=id(args[4]);if(id==null){usage(sender);return;}observedSave(sender,"administrator_mob_remove",()->directory.removeMob(dungeon,room.id(),id)).whenComplete((value,failure)->saved(sender,failure,value!=null&&value.isPresent()?"Removed mob slot "+id+".":"Mob slot not found."));return;}if(args.length==4&&args[3].equals("list")){if(room.mobs().isEmpty())sender.sendMessage("No ordinary mob slots in this room.");else room.mobs().forEach(value->sender.sendMessage(value.id()+" "+value.type().name().toLowerCase(Locale.ROOT)+" "+value.name()));completedRead(adminAudit==null?null:adminAudit.current());return;}usage(sender);}
private void effect(CommandSender sender,Player player,UUID dungeon,String[] args){var room=standing(sender,player);if(room==null)return;if(args.length>=7&&args[3].equals("add")){DungeonState.EffectTarget target;try{target=DungeonState.EffectTarget.valueOf(args[4].toUpperCase(Locale.ROOT));}catch(IllegalArgumentException invalid){usage(sender);return;}String key=args[5].contains(":")?args[5]:"minecraft:"+args[5];var namespaced=NamespacedKey.fromString(key);Integer level=integer(args[6]);boolean particles=args.length<8||Boolean.parseBoolean(args[7]);if(namespaced==null||PotionEffectType.getByKey(namespaced)==null||level==null||args.length>8||args.length==8&&!Set.of("true","false").contains(args[7])){usage(sender);return;}observedSave(sender,"administrator_effect_add",()->directory.addEffect(dungeon,room.id(),target,key,level,particles)).whenComplete((value,failure)->saved(sender,failure,"Added room effect "+(value==null?"":value.id())+"."));return;}if(args.length==5&&args[3].equals("remove")){UUID id=id(args[4]);if(id==null){usage(sender);return;}observedSave(sender,"administrator_effect_remove",()->directory.removeEffect(dungeon,room.id(),id)).whenComplete((value,failure)->saved(sender,failure,value!=null&&value.isPresent()?"Removed room effect "+id+".":"Room effect not found."));return;}usage(sender);}
private void reward(CommandSender sender,String[] args){if(args.length<3||args.length>5){usage(sender);return;}UUID dungeon=id(args[2]);var current=dungeon==null?null:directory.find(dungeon).orElse(null);if(current==null){sender.sendMessage("Dungeon not found.");return;}if(args.length==3){sender.sendMessage(current.rewardConfigured()?"Dungeon "+dungeon+" completion reward is "+current.completionReward().xp()+" XP and "+current.completionReward().coins()+" coins.":"Dungeon "+dungeon+" completion reward is not configured.");return;}if(current.enabled()||adventures.offerOpen(dungeon)||adventures.active().stream().anyMatch(quest->quest.site().equals(dungeon))){sender.sendMessage("Dungeon reward update requires disabled, closed dungeon state without accepted quests.");return;}if(controller.beingEdited(dungeon)&&(!(sender instanceof Player player)||!controller.editing(player.getUniqueId()).filter(dungeon::equals).isPresent())){sender.sendMessage("Dungeon reward update refused: another administrator owns the editing lease.");return;}BigInteger xp=args.length==5?whole(args[3]):null,coins=args.length==5?whole(args[4]):null;if(xp==null||coins==null){usage(sender);return;}var audit=auditEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();directory.setCompletionRewardWithEvidence(dungeon,xp,coins).whenComplete((change,failure)->{if(failure==null&&audit!=null)try{audit.rewardChanged(operation,actor,change);}catch(RuntimeException ignored){}saved(sender,failure,"Set dungeon completion reward to "+xp+" XP and "+coins+" coins.");});}
private void boss(CommandSender sender,Player player,UUID dungeon,String[] args){var room=standing(sender,player);if(room==null)return;if(args.length==5&&args[3].equals("assign-sheet")){assignCharacterBoss(sender,player,dungeon,room,args[4]);return;}if(args.length>=5&&args[3].equals("mob")){var type=entity(args[4]);if(!ordinary(type)){sender.sendMessage("Unsupported living boss type.");return;}var location=player.getLocation();observedSave(sender,"administrator_native_boss",()->directory.setBoss(dungeon,room.id(),type,join(args,5),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Configured native boss "+type.name().toLowerCase(Locale.ROOT)+"."));return;}if(args.length==4&&args[3].equals("clear")){observedSave(sender,"administrator_native_boss_clear",()->directory.clearBoss(dungeon,room.id())).whenComplete((value,failure)->saved(sender,failure,"Cleared the room boss."));return;}usage(sender);}
private void assignCharacterBoss(CommandSender sender,Player player,UUID dungeon,DungeonState.Room room,String rawMultiplier){BigDecimal multiplier;try{if(!rawMultiplier.matches("(?:0|[1-9][0-9]*)(?:\\.[0-9]{1,3})?"))throw new NumberFormatException();multiplier=new BigDecimal(rawMultiplier);}catch(NumberFormatException invalid){usage(sender);return;}var held=player.getInventory().getItemInMainHand();var sheetIdentity=sheets.identity(held).orElse(null);var character=sheetIdentity==null?null:sheetIdentity.character();if(character==null||held.getAmount()!=1){sender.sendMessage("Hold exactly one authentic living character sheet in your main hand.");return;}if(physicalCopies(character)!=1){sender.sendMessage("Character boss assignment requires one unambiguous physical sheet.");return;}if(activeCharacter.test(character)){sender.sendMessage("That character has an active equipment session.");return;}if(partyCharacter.test(character)){sender.sendMessage("That character must leave its party before boss assignment.");return;}var audit=characterBossEvents;var request=audit==null?null:audit.request(sender);characters.apply(character).whenComplete((loaded,failure)->{if(failure!=null||loaded==null||loaded.isEmpty()||loaded.orElseThrow().dead()||loaded.orElseThrow().health().signum()<=0){respond(sender,()->sender.sendMessage("Character boss assignment refused: the saved living character could not be verified."));return;}var expected=loaded.orElseThrow();if(!sheetIdentity.generation().equals(expected.sheetGeneration())||(sheetIdentity.legacy()&&expected.sheetGeneration().signum()!=0)){respond(sender,()->sender.sendMessage("Character boss assignment refused: that sheet generation is no longer authorized."));return;}var assignment=directory.assignCharacterBoss(dungeon,room.id(),expected,multiplier);assignment.whenComplete((custody,saveFailure)->{if(saveFailure!=null){respond(sender,()->sender.sendMessage("Character boss assignment failed before sheet custody changed."));return;}if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.custodySaved(audit.assignment(request,publication,dungeon,room.id(),custody)));}catch(RuntimeException ignored){/* Saved custody observation never gates native revalidation or consumption. */}characters.apply(character).whenComplete((fresh,readFailure)->respond(sender,()->{if(readFailure!=null||fresh==null||fresh.isEmpty()||!fresh.orElseThrow().equals(expected)||activeCharacter.test(character)||partyCharacter.test(character)){var rollback=directory.cancelAssignment(dungeon,custody.operation());rollback.whenComplete((applied,rollbackFailure)->{if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.rolledBack(audit.assignment(request,publication,dungeon,room.id(),custody),rollbackFailure==null&&Boolean.TRUE.equals(applied),DungeonDirectory.publication(rollback).orElse(null),"saved_character_changed"));}catch(RuntimeException ignored){/* Original rollback observation cannot change character/custody authority. */}respond(sender,()->sender.sendMessage(rollbackFailure==null?"Character boss assignment cancelled because the saved character changed.":"Character boss custody was saved but assignment rollback could not be confirmed; recover it before editing."));});return;}var current=player.getInventory().getItemInMainHand();if(!player.isOnline()||physicalCopies(character)!=1||current.getAmount()!=1||!sheets.authorizes(current,expected)){var rollback=directory.cancelAssignment(dungeon,custody.operation());rollback.whenComplete((applied,rollbackFailure)->{if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.rolledBack(audit.assignment(request,publication,dungeon,room.id(),custody),rollbackFailure==null&&Boolean.TRUE.equals(applied),DungeonDirectory.publication(rollback).orElse(null),"held_sheet_changed"));}catch(RuntimeException ignored){/* Original rollback observation cannot change inventory/custody authority. */}respond(sender,()->sender.sendMessage(rollbackFailure==null?"Character boss assignment cancelled because the held sheet changed.":"Character boss custody was saved but sheet consumption could not be confirmed; recover it before editing."));});return;}player.getInventory().setItemInMainHand(null);if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.assigned(audit.assignment(request,publication,dungeon,room.id(),custody)));}catch(RuntimeException ignored){/* Optional observation cannot interrupt physical consumption. */}sender.sendMessage("Assigned character "+custody.character().name()+" as the dungeon boss at "+custody.multiplier().toPlainString()+"x stats; its sheet is now in durable custody.");}));});});}
private void bossCommand(CommandSender sender,String[] args){if(args.length!=4||!args[2].equals("recover-sheet")||!(sender instanceof Player player)){usage(sender);return;}UUID dungeon=id(args[3]);if(dungeon==null){usage(sender);return;}recoverCharacterBoss(sender,player,dungeon);}
private void recoverCharacterBoss(CommandSender sender,Player player,UUID dungeon){var definition=directory.find(dungeon).orElse(null);var custody=directory.custodyForDungeon(dungeon).orElse(null);if(definition==null||custody==null){sender.sendMessage("Dungeon character boss custody was not found.");return;}var catalog=adventures.snapshot().catalog();boolean offered=catalog!=null&&adventures.offerOpen(dungeon);boolean accepted=adventures.active().stream().anyMatch(quest->quest.site().equals(dungeon));if(definition.enabled()||offered||accepted||controller.beingEdited(dungeon)||controller.editing(player.getUniqueId()).isPresent()||controller.occupied(dungeon)){sender.sendMessage("Recovery requires a disabled, closed, unedited and unoccupied dungeon with no accepted quests.");return;}var physical=plugin.getServer().getOnlinePlayers().stream().flatMap(holder->Arrays.stream(holder.getInventory().getContents()).filter(Objects::nonNull).filter(item->sheets.identify(item).filter(custody.character().id()::equals).isPresent()).map(item->Map.entry(holder,item))).toList();if(physical.size()>1||physical.size()==1&&physical.getFirst().getKey()!=player){sender.sendMessage("Recovery refused because existing physical-sheet custody is ambiguous.");return;}boolean delivered=!physical.isEmpty()||custody.recovery()!=null&&Arrays.stream(player.getInventory().getContents()).anyMatch(item->sheets.hasRecovery(item,custody.recovery().operation()));if(!delivered&&player.getInventory().firstEmpty()<0){sender.sendMessage("One empty inventory slot is required before recovery.");return;}var audit=characterBossEvents;var request=audit==null?null:audit.request(sender);var preparation=directory.prepareRecovery(dungeon,player.getUniqueId());preparation.whenComplete((prepared,failure)->respond(sender,()->{if(failure!=null){sender.sendMessage("Character boss recovery could not be prepared; custody is retained.");return;}var operation=prepared.recovery().operation();org.bukkit.inventory.ItemStack sheet=null;for(var item:player.getInventory().getContents())if(sheets.hasRecovery(item,operation)||sheets.identify(item).filter(prepared.character().id()::equals).isPresent()){sheet=item;break;}if(sheet==null){int slot=player.getInventory().firstEmpty();if(slot<0){sender.sendMessage("Character boss recovery is prepared, but one empty inventory slot is required.");return;}sheet=sheets.create(prepared.character());sheets.markRecovery(sheet,operation);player.getInventory().setItem(slot,sheet);}var item=sheet;games.dmg.fantasystick.events.CharacterBossEventBridge.Facts deliveryFacts=null;if(audit!=null)try{var view=DungeonDirectory.publication(preparation).flatMap(publication->publication.after().dungeons().stream().filter(value->value.id().equals(dungeon)).findFirst()).orElse(definition);var originalRoom=view.rooms().stream().filter(value->value.boss()!=null&&value.boss().character()!=null&&value.boss().character().operation().equals(prepared.operation())).findFirst().orElseThrow();deliveryFacts=audit.custody(request,view,originalRoom.id(),prepared);}catch(RuntimeException ignored){/* Delivery does not depend on optional metadata. */}var facts=deliveryFacts;var completion=directory.completeRecovery(dungeon,operation);completion.whenComplete((completed,completeFailure)->{if(completeFailure==null&&Boolean.TRUE.equals(completed)&&facts!=null)try{DungeonDirectory.publication(completion).ifPresent(publication->audit.recovered(facts,operation,publication,"exact_authorized_sheet_delivered"));}catch(RuntimeException ignored){/* Durable completion stays authoritative independently of feedback. */}if(facts!=null&&(completeFailure!=null||!Boolean.TRUE.equals(completed)))try{audit.recoveryPending(facts,operation,completeFailure!=null?"failed_final_source_save":"completion_not_acknowledged");}catch(RuntimeException ignored){/* Pending recovery observation cannot change custody or native delivery. */}respond(sender,()->{if(completeFailure!=null||!completed){sender.sendMessage("Recovery sheet delivery is retained, but durable custody completion must be retried.");return;}sheets.clearRecovery(item);sender.sendMessage("Recovered character sheet for "+prepared.character().name()+" from dungeon "+dungeon+"; configure another boss before enabling it.");});});}));}
private void teleport(CommandSender sender,String[] args){if(args.length!=3){usage(sender);return;}if(!(sender instanceof Player)){sender.sendMessage("Dungeon teleport requires a player.");return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}var dungeon=directory.find(id).orElse(null);if(dungeon==null){sender.sendMessage("Dungeon not found.");return;}teleports.teleport(sender,"Dungeon",target(dungeon),()->directory.find(id).map(DungeonCommands::target));}
private void reward(CommandSender sender,String[] args){if(args.length<3||args.length>5){usage(sender);return;}UUID dungeon=id(args[2]);var current=dungeon==null?null:directory.find(dungeon).orElse(null);if(current==null){refused("not_found");sender.sendMessage("Dungeon not found.");return;}if(args.length==3){sender.sendMessage(current.rewardConfigured()?"Dungeon "+dungeon+" completion reward is "+current.completionReward().xp()+" XP and "+current.completionReward().coins()+" coins.":"Dungeon "+dungeon+" completion reward is not configured.");completedRead(adminAudit==null?null:adminAudit.current());return;}if(current.enabled()||adventures.offerOpen(dungeon)||adventures.active().stream().anyMatch(quest->quest.site().equals(dungeon))){refused("owner_refused");sender.sendMessage("Dungeon reward update requires disabled, closed dungeon state without accepted quests.");return;}if(controller.beingEdited(dungeon)&&(!(sender instanceof Player player)||!controller.editing(player.getUniqueId()).filter(dungeon::equals).isPresent())){refused("owner_refused");sender.sendMessage("Dungeon reward update refused: another administrator owns the editing lease.");return;}BigInteger xp=args.length==5?whole(args[3]):null,coins=args.length==5?whole(args[4]):null;if(xp==null||coins==null){usage(sender);return;}var audit=auditEvents;var actor=audit==null?null:audit.actor(sender);var operation=UUID.randomUUID();var action=adminAudit==null?null:adminAudit.current();directory.setCompletionRewardWithEvidence(dungeon,xp,coins).whenComplete((change,failure)->{if(failure==null&&audit!=null)try{audit.rewardChanged(operation,actor,change);}catch(RuntimeException ignored){}if(failure==null&&adminAudit!=null)adminAudit.result(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",Map.of("domain_operation_id",operation,"domain_event_id",UUID.nameUUIDFromBytes(("fantasystick:fishing:"+operation+":dungeon.reward_changed").getBytes(java.nio.charset.StandardCharsets.UTF_8))));else if(failure!=null)savedResult(action,failure,null,null);saved(sender,failure,"Set dungeon completion reward to "+xp+" XP and "+coins+" coins.");});}
private void boss(CommandSender sender,Player player,UUID dungeon,String[] args){var room=standing(sender,player);if(room==null)return;if(args.length==5&&args[3].equals("assign-sheet")){assignCharacterBoss(sender,player,dungeon,room,args[4]);return;}if(args.length>=5&&args[3].equals("mob")){var type=entity(args[4]);if(!ordinary(type)){refused("owner_refused");sender.sendMessage("Unsupported living boss type.");return;}var location=player.getLocation();observedSave(sender,"administrator_native_boss",()->directory.setBoss(dungeon,room.id(),type,join(args,5),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch())).whenComplete((value,failure)->saved(sender,failure,"Configured native boss "+type.name().toLowerCase(Locale.ROOT)+"."));return;}if(args.length==4&&args[3].equals("clear")){observedSave(sender,"administrator_native_boss_clear",()->directory.clearBoss(dungeon,room.id())).whenComplete((value,failure)->saved(sender,failure,"Cleared the room boss."));return;}usage(sender);}
private void assignCharacterBoss(CommandSender sender,Player player,UUID dungeon,DungeonState.Room room,String rawMultiplier){BigDecimal multiplier;try{if(!rawMultiplier.matches("(?:0|[1-9][0-9]*)(?:\\.[0-9]{1,3})?"))throw new NumberFormatException();multiplier=new BigDecimal(rawMultiplier);}catch(NumberFormatException invalid){usage(sender);return;}var held=player.getInventory().getItemInMainHand();var sheetIdentity=sheets.identity(held).orElse(null);var character=sheetIdentity==null?null:sheetIdentity.character();if(character==null||held.getAmount()!=1){refused("owner_refused");sender.sendMessage("Hold exactly one authentic living character sheet in your main hand.");return;}if(physicalCopies(character)!=1){refused("owner_refused");sender.sendMessage("Character boss assignment requires one unambiguous physical sheet.");return;}if(activeCharacter.test(character)){refused("owner_refused");sender.sendMessage("That character has an active equipment session.");return;}if(partyCharacter.test(character)){refused("owner_refused");sender.sendMessage("That character must leave its party before boss assignment.");return;}var audit=characterBossEvents;var request=audit==null?null:audit.request(sender);var adminAction=adminAudit==null?null:adminAudit.current();characters.apply(character).whenComplete((loaded,failure)->{if(failure!=null||loaded==null||loaded.isEmpty()||loaded.orElseThrow().dead()||loaded.orElseThrow().health().signum()<=0){adminResult(adminAction,failure!=null?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,failure!=null?"operation_failed":"owner_refused",null,null);respond(sender,()->sender.sendMessage("Character boss assignment refused: the saved living character could not be verified."));return;}var expected=loaded.orElseThrow();if(!sheetIdentity.generation().equals(expected.sheetGeneration())||(sheetIdentity.legacy()&&expected.sheetGeneration().signum()!=0)){adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);respond(sender,()->sender.sendMessage("Character boss assignment refused: that sheet generation is no longer authorized."));return;}var assignment=directory.assignCharacterBoss(dungeon,room.id(),expected,multiplier);assignment.whenComplete((custody,saveFailure)->{if(saveFailure!=null){savedResult(adminAction,saveFailure,null,null);respond(sender,()->sender.sendMessage("Character boss assignment failed before sheet custody changed."));return;}if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.custodySaved(audit.assignment(request,publication,dungeon,room.id(),custody)));}catch(RuntimeException ignored){/* Saved custody observation never gates native revalidation or consumption. */}characters.apply(character).whenComplete((fresh,readFailure)->respond(sender,()->{if(readFailure!=null||fresh==null||fresh.isEmpty()||!fresh.orElseThrow().equals(expected)||activeCharacter.test(character)||partyCharacter.test(character)){var rollback=directory.cancelAssignment(dungeon,custody.operation());rollback.whenComplete((applied,rollbackFailure)->{if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.rolledBack(audit.assignment(request,publication,dungeon,room.id(),custody),rollbackFailure==null&&Boolean.TRUE.equals(applied),DungeonDirectory.publication(rollback).orElse(null),"saved_character_changed"));}catch(RuntimeException ignored){/* Original rollback observation cannot change character/custody authority. */}adminResult(adminAction,rollbackFailure==null&&Boolean.TRUE.equals(applied)?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,rollbackFailure==null&&Boolean.TRUE.equals(applied)?"owner_refused":"operation_uncertain",null,null);respond(sender,()->sender.sendMessage(rollbackFailure==null?"Character boss assignment cancelled because the saved character changed.":"Character boss custody was saved but assignment rollback could not be confirmed; recover it before editing."));});return;}var current=player.getInventory().getItemInMainHand();if(!player.isOnline()||physicalCopies(character)!=1||current.getAmount()!=1||!sheets.authorizes(current,expected)){var rollback=directory.cancelAssignment(dungeon,custody.operation());rollback.whenComplete((applied,rollbackFailure)->{if(audit!=null)try{DungeonDirectory.publication(assignment).ifPresent(publication->audit.rolledBack(audit.assignment(request,publication,dungeon,room.id(),custody),rollbackFailure==null&&Boolean.TRUE.equals(applied),DungeonDirectory.publication(rollback).orElse(null),"held_sheet_changed"));}catch(RuntimeException ignored){/* Original rollback observation cannot change inventory/custody authority. */}adminResult(adminAction,rollbackFailure==null&&Boolean.TRUE.equals(applied)?games.dmg.fantasystick.events.AdminActionEventBridgeLine truncated
private void bossCommand(CommandSender sender,String[] args){if(args.length!=4||!args[2].equals("recover-sheet")||!(sender instanceof Player player)){if(!(sender instanceof Player))refused("sender_unsupported");usage(sender);return;}UUID dungeon=id(args[3]);if(dungeon==null){usage(sender);return;}recoverCharacterBoss(sender,player,dungeon);}
private void recoverCharacterBoss(CommandSender sender,Player player,UUID dungeon){var definition=directory.find(dungeon).orElse(null);var custody=directory.custodyForDungeon(dungeon).orElse(null);if(definition==null||custody==null){refused("owner_refused");sender.sendMessage("Dungeon character boss custody was not found.");return;}var catalog=adventures.snapshot().catalog();boolean offered=catalog!=null&&adventures.offerOpen(dungeon);boolean accepted=adventures.active().stream().anyMatch(quest->quest.site().equals(dungeon));if(definition.enabled()||offered||accepted||controller.beingEdited(dungeon)||controller.editing(player.getUniqueId()).isPresent()||controller.occupied(dungeon)){refused("owner_refused");sender.sendMessage("Recovery requires a disabled, closed, unedited and unoccupied dungeon with no accepted quests.");return;}var physical=authorizedPhysical(custody.character());if(ambiguousPhysical(physical,player)){refused("owner_refused");sender.sendMessage("Recovery refused because existing physical-sheet custody is ambiguous.");return;}boolean delivered=!physical.isEmpty();if(!delivered&&player.getInventory().firstEmpty()<0){refused("owner_refused");sender.sendMessage("One empty inventory slot is required before recovery.");return;}var audit=characterBossEvents;var request=audit==null?null:audit.request(sender);var adminAction=adminAudit==null?null:adminAudit.current();var preparation=directory.prepareRecovery(dungeon,player.getUniqueId());preparation.whenComplete((prepared,failure)->respond(sender,()->{if(failure!=null){savedResult(adminAction,failure,null,null);sender.sendMessage("Character boss recovery could not be prepared; custody is retained.");return;}var operation=prepared.recovery().operation();var currentPhysical=authorizedPhysical(prepared.character());if(ambiguousPhysical(currentPhysical,player)){adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);sender.sendMessage("Recovery refused because existing physical-sheet custody is ambiguous; prepared custody is retained.");return;}org.bukkit.inventory.ItemStack sheet=currentPhysical.isEmpty()?null:currentPhysical.getFirst().getValue();if(sheet==null){int slot=player.getInventory().firstEmpty();if(slot<0){adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);sender.sendMessage("Character boss recovery is prepared, but one empty inventory slot is required.");return;}sheet=sheets.create(prepared.character());sheets.markRecovery(sheet,operation);player.getInventory().setItem(slot,sheet);sheet=player.getInventory().getItem(slot);}if(!sheets.authorizes(sheet,prepared.character())){adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);sender.sendMessage("Character boss recovery is prepared, but authorized native sheet delivery could not be verified; custody is retained.");return;}var finalPhysical=authorizedPhysical(prepared.character());if(finalPhysical.size()!=1||ambiguousPhysical(finalPhysical,player)){adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"owner_refused",null,null);sender.sendMessage("Recovery refused because native physical-sheet delivery is ambiguous; prepared custody is retained.");return;}var item=finalPhysical.getFirst().getValue();games.dmg.fantasystick.events.CharacterBossEventBridge.Facts deliveryFacts=null;if(audit!=null)try{var view=DungeonDirectory.publication(preparation).flatMap(publication->publication.after().dungeons().stream().filter(value->value.id().equals(dungeon)).findFirst()).orElse(definition);var originalRoom=view.rooms().stream().filter(value->value.boss()!=null&&value.boss().character()!=null&&value.boss().character().operation().equals(prepared.operation())).findFirst().orElseThrow();deliveryFacts=audit.custody(request,view,originalRoom.id(),prepared);}catch(RuntimeException ignored){/* Delivery does not depend on optional metadata. */}var facts=deliveryFacts;var completion=directory.completeRecovery(dungeon,operation);completion.whenComplete((completed,completeFailure)->{if(completeFailure==null&&Boolean.TRUE.equals(completed)&&facts!=null)try{DungeonDirectory.publication(completion).ifPresent(publication->audit.recovered(facts,operation,publication,"exact_authorized_sheet_delivered"));}catch(RuntimeException ignored){/* Durable completion stays authoritative independently of feedback. */}if(completeFailure==null&&Boolean.TRUE.equals(completed)){if(facts!=null&&DungeonDirectory.publication(completion).isPresent())bossResult(adminAction,operation,"dungeon.character_boss.recovered");else adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",operation,null);}else adminResult(adminAction,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",null,null);if(facts!=null&&(compLine truncated
private void teleport(CommandSender sender,String[] args){if(args.length!=3){usage(sender);return;}if(!(sender instanceof Player)){refused("sender_unsupported");sender.sendMessage("Dungeon teleport requires a player.");return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}var dungeon=directory.find(id).orElse(null);if(dungeon==null){refused("not_found");sender.sendMessage("Dungeon not found.");return;}var action=adminAudit==null?null:adminAudit.current();teleports.teleport(sender,"Dungeon",target(dungeon),()->directory.find(id).map(DungeonCommands::target),outcome->adminResult(action,outcome,outcome==games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED?"acknowledged":outcome==games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED?"operation_failed":outcome==games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN?"operation_uncertain":"owner_refused",null,null));}
private static AdventureAdminTeleport.Target target(DungeonState.Dungeon dungeon){var entrance=dungeon.entrance();return new AdventureAdminTeleport.Target(dungeon.id(),dungeon.name(),"dungeon entrance",dungeon.world(),entrance.x(),entrance.y(),entrance.z(),entrance.yaw(),entrance.pitch(),false);}
private void enable(CommandSender sender,String[] args){if(args.length!=3){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}observedSave(sender,"administrator_enable",()->controller.enable(id)).whenComplete((value,failure)->respond(sender,()->sender.sendMessage(failure==null?"Enabled dungeon "+id+" for later adventure catalogs.":"Dungeon enable refused: validate completion reward, rooms, boss, overlap and persistence.")));}
private void disable(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}var request=request(sender);controller.disableWithEvidence(id,publication->{if(request.events()!=null)try{request.events().definitionSaved(request.operation(),request.actor(),publication,"administrator_disable_saved");}catch(RuntimeException ignored){}}).whenComplete((value,failure)->{respond(sender,()->sender.sendMessage(failure!=null?"Dungeon disable failed; retained state is authoritative.":value.applied()?"Disabled and closed dungeon "+id+".":"Dungeon not found."));});}
private void open(CommandSender sender,String[] args){if(args.length!=3){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}var request=request(sender);controller.openWithEvidence(id).whenComplete((value,failure)->{if(failure==null&&value.publication().changed()&&request.events()!=null)try{request.events().offer("dungeon.offer.opened",request.operation(),request.actor(),value.dungeon(),value.publication().after(),"administrator_open");}catch(RuntimeException ignored){}respond(sender,()->sender.sendMessage(failure==null?"Opened dungeon "+id+" in generation "+value.publication().after().revision()+".":"Dungeon open refused: it is invalid, disabled, defeated or the offer limit was reached."));});}
private void close(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}var request=request(sender);var definition=directory.find(id).orElse(null);var catalog=adventures.snapshot().catalog();controller.closeOffer(id).whenComplete((value,failure)->{if(failure==null&&Boolean.TRUE.equals(value)&&definition!=null&&catalog!=null&&request.events()!=null)try{request.events().offer("dungeon.offer.closed",request.operation(),request.actor(),definition,catalog,"administrator_close");}catch(RuntimeException ignored){}respond(sender,()->sender.sendMessage(failure!=null?"Dungeon close failed; retained state is authoritative.":value?"Closed dungeon "+id+" for this generation.":"Dungeon was not open."));});}
private record AuditRequest(games.dmg.fantasystick.events.DungeonAuditEventBridge events,games.dmg.fantasystick.events.CampEventBridge.Actor actor,UUID operation){}
private AuditRequest request(CommandSender sender){var events=ownerEvents;return new AuditRequest(events,events==null?null:events.actor(sender),UUID.randomUUID());}
private void disable(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}confirm();var request=request(sender);controller.disableWithEvidence(id,publication->{if(request.events()!=null)try{request.events().definitionSaved(request.operation(),request.actor(),publication,"administrator_disable_saved");}catch(RuntimeException ignored){}}).whenComplete((value,failure)->{if(failure!=null)savedResult(request.action(),failure,null,null);else if(!value.applied())refusedSave(request.action());else{var publication=value.publication();boolean changed=publication!=null&&publication.before().dungeons().stream().anyMatch(before->before.id().equals(id)&&before.enabled())&&publication.after().dungeons().stream().anyMatch(after->after.id().equals(id)&&!after.enabled());savedResult(request.action(),null,request.operation(),changed?"dungeon.disabled":null);}respond(sender,()->sender.sendMessage(failure!=null?"Dungeon disable failed; retained state is authoritative.":value.applied()?"Disabled and closed dungeon "+id+".":"Dungeon not found."));});}
private void open(CommandSender sender,String[] args){if(args.length!=3){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}if(directory.find(id).isEmpty()){refused("not_found");sender.sendMessage("Dungeon command refused: Dungeon is not enabled.");return;}var request=request(sender);controller.openWithEvidence(id).whenComplete((value,failure)->{if(failure==null&&value.publication().changed()&&request.events()!=null)try{request.events().offer("dungeon.offer.opened",request.operation(),request.actor(),value.dungeon(),value.publication().after(),"administrator_open");}catch(RuntimeException ignored){}if(failure!=null){Throwable cause=failure;while(cause instanceof java.util.concurrent.CompletionException&&cause.getCause()!=null)cause=cause.getCause();adminResult(request.action(),cause instanceof java.io.IOException?games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED:games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,cause instanceof java.io.IOException?"operation_failed":"owner_refused",null,null);}else if(!value.publication().changed())adminResult(request.action(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"no_change",null,null);else savedResult(request.action(),null,request.operation(),"dungeon.offer.opened");respond(sender,()->sender.sendMessage(failure==null?"Opened dungeon "+id+" in generation "+value.publication().after().revision()+".":"Dungeon open refused: it is invalid, disabled, defeated or the offer limit was reached."));});}
private void close(CommandSender sender,String[] args){if(args.length!=4||!args[3].equals("confirm")){usage(sender);return;}UUID id=id(args[2]);if(id==null){usage(sender);return;}confirm();var request=request(sender);var definition=directory.find(id).orElse(null);var catalog=adventures.snapshot().catalog();controller.closeOffer(id).whenComplete((value,failure)->{if(failure==null&&Boolean.TRUE.equals(value)&&definition!=null&&catalog!=null&&request.events()!=null)try{request.events().offer("dungeon.offer.closed",request.operation(),request.actor(),definition,catalog,"administrator_close");}catch(RuntimeException ignored){}if(failure!=null)savedResult(request.action(),failure,null,null);else if(Boolean.TRUE.equals(value))savedResult(request.action(),null,request.operation(),definition!=null&&catalog!=null?"dungeon.offer.closed":null);else refusedSave(request.action());respond(sender,()->sender.sendMessage(failure!=null?"Dungeon close failed; retained state is authoritative.":value?"Closed dungeon "+id+" for this generation.":"Dungeon was not open."));});}
private record AuditRequest(games.dmg.fantasystick.events.DungeonAuditEventBridge events,games.dmg.fantasystick.events.CampEventBridge.Actor actor,UUID operation,games.dmg.fantasystick.events.AdminActionEventBridge.Action action){}
private AuditRequest request(CommandSender sender){var events=ownerEvents;return new AuditRequest(events,events==null?null:events.actor(sender),UUID.randomUUID(),adminAudit==null?null:adminAudit.current());}
private <T>java.util.concurrent.CompletionStage<T> observedSave(CommandSender sender,String reason,java.util.function.Supplier<? extends java.util.concurrent.CompletionStage<T>> work){return observedSave(request(sender),reason,work);}
private <T>java.util.concurrent.CompletionStage<T> observedSave(AuditRequest request,String reason,java.util.function.Supplier<? extends java.util.concurrent.CompletionStage<T>> work){var source=work.get();return source.whenComplete((value,failure)->{if(failure==null&&request.events()!=null)try{DungeonDirectory.publication(source).ifPresent(publication->request.events().definitionSaved(request.operation(),request.actor(),publication,reason));}catch(RuntimeException ignored){/* Audit is never authoring authority. */}});}
private <T>java.util.concurrent.CompletionStage<T> observedSave(AuditRequest request,String reason,java.util.function.Supplier<? extends java.util.concurrent.CompletionStage<T>> work){
java.util.concurrent.CompletionStage<T> source;
try{source=work.get();}catch(RuntimeException failure){savedResult(request.action(),failure,null,null);throw failure;}
return source.whenComplete((value,failure)->{
if(failure!=null){savedResult(request.action(),failure,null,null);return;}
var publication=DungeonDirectory.publication(source).orElse(null);
if(publication==null||publication.before().equals(publication.after())||value instanceof Optional<?> optional&&optional.isEmpty()||value instanceof Boolean applied&&!applied){refusedSave(request.action());return;}
var types=definitionTypes(publication);
if(request.events()!=null)try{request.events().definitionSaved(request.operation(),request.actor(),publication,reason);}catch(RuntimeException ignored){/* Audit is never authoring authority. */}
if(types.size()==1)savedResult(request.action(),null,request.operation(),types.getFirst());
else adminResult(request.action(),games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",request.operation(),null);
});
}
private void refusedSave(games.dmg.fantasystick.events.AdminActionEventBridge.Action action){adminResult(action,games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED,"no_change",null,null);}
private static List<String> definitionTypes(DungeonDirectory.Publication publication){
var before=publication.before().dungeons();var after=publication.after().dungeons();var types=new ArrayList<String>();
for(var prior:before){var current=after.stream().filter(value->value.id().equals(prior.id())).findFirst().orElse(null);
if(current==null){types.add("dungeon.removed");continue;}if(prior.equals(current))continue;
if(!prior.entrance().equals(current.entrance()))types.add("dungeon.entrance_changed");
if(prior.enabled()!=current.enabled())types.add(current.enabled()?"dungeon.enabled":"dungeon.disabled");
for(var room:prior.rooms())if(current.rooms().stream().noneMatch(value->value.id().equals(room.id())))types.add("dungeon.room.removed");
for(var room:current.rooms()){var old=prior.rooms().stream().filter(value->value.id().equals(room.id())).findFirst().orElse(null);
if(old==null){types.add("dungeon.room.created");continue;}
for(var slot:room.mobs())if(old.mobs().stream().noneMatch(value->value.id().equals(slot.id())))types.add("dungeon.mob_slot.added");
for(var slot:old.mobs())if(room.mobs().stream().noneMatch(value->value.id().equals(slot.id())))types.add("dungeon.mob_slot.removed");
for(var effect:room.effects())if(old.effects().stream().noneMatch(value->value.id().equals(effect.id())))types.add("dungeon.effect.added");
for(var effect:old.effects())if(room.effects().stream().noneMatch(value->value.id().equals(effect.id())))types.add("dungeon.effect.removed");
if(!Objects.equals(old.boss(),room.boss()))types.add(room.boss()==null?"dungeon.boss.cleared":"dungeon.boss.configured");
}
}
return types;
}
public List<String> complete(CommandSender sender,String[] args){if(!sender.hasPermission(PERMISSION))return List.of();if(args.length==1)return matching(List.of("dungeon"),args[0]);if(args.length==2&&args[0].equals("dungeon"))return matching(sender instanceof Player?List.of("boss","close","create","disable","edit","enable","entrance","list","mode","open","remove","reward","room","teleport"):List.of("close","disable","enable","list","mode","open","remove","reward"),args[1]);if(!args[0].equals("dungeon"))return List.of();if(args.length==3&&args[1].equals("boss"))return matching(List.of("recover-sheet"),args[2]);if(args.length==4&&args[1].equals("boss")&&args[2].equals("recover-sheet"))return matching(directory.snapshot().dungeons().stream().filter(value->recoverable(value.id())).map(value->value.id().toString()).toList(),args[3]);if(args.length==3&&args[1].equals("create"))return matching(List.of("--mode"),args[2]);if(args.length==4&&args[1].equals("create")&&args[2].equals("--mode"))return matching(modeValues(),args[3]);if(args.length==3&&Set.of("close","disable","enable","mode","open","remove","reward","teleport").contains(args[1]))return matching(directory.snapshot().dungeons().stream().map(v->v.id().toString()).toList(),args[2]);if(args.length==4&&args[1].equals("mode"))return matching(modeValues(),args[3]);if((args.length==4||args.length==5)&&args[1].equals("reward")){UUID dungeon=id(args[2]);var current=dungeon==null?null:directory.find(dungeon).orElse(null);if(current==null)return List.of();var values=new ArrayList<>(List.of("0","10","100","2147483647"));values.add((args.length==4?current.completionReward().xp():current.completionReward().coins()).toString());return matching(values,args[args.length-1]);}if(args.length==4&&Set.of("close","disable","remove").contains(args[1]))return matching(List.of("confirm"),args[3]);if(args.length==3&&args[1].equals("edit"))return matching(List.of("done","start"),args[2]);if(args.length==4&&args[1].equals("edit")&&args[2].equals("start"))return matching(directory.snapshot().dungeons().stream().map(v->v.id().toString()).toList(),args[3]);if(args.length==5&&args[1].equals("edit")&&args[2].equals("start"))return matching(List.of("confirm"),args[4]);if(args.length==3&&args[1].equals("entrance"))return matching(List.of("set"),args[2]);if(args.length==3&&args[1].equals("room"))return matching(List.of("boss","create","effect","list","mob","remove"),args[2]);if(args.length==4&&args[1].equals("room")&&args[2].equals("create"))return matching(List.of("corner","radius"),args[3]);if(args.length>=5&&args.length<=7&&args[1].equals("room")&&args[2].equals("create"))return matching(List.of("1","3","8","128","256"),args[args.length-1]);if(args.length==4&&args[1].equals("room")&&args[2].equals("remove")&&sender instanceof Player player){var id=controller.editing(player.getUniqueId()).orElse(null);return id==null?List.of():matching(directory.find(id).map(DungeonState.Dungeon::rooms).orElse(List.of()).stream().map(v->v.id().toString()).toList(),args[3]);}if(args.length==4&&args[1].equals("room")&&args[2].equals("mob"))return matching(List.of("add","list","remove"),args[3]);if(args.length==5&&args[1].equals("room")&&args[2].equals("mob")&&args[3].equals("add"))return matching(entityNames(),args[4]);if(args.length==5&&args[1].equals("room")&&args[2].equals("mob")&&args[3].equals("remove")&&sender instanceof Player player){var room=controller.standingRoom(player).orElse(null);return room==null?List.of():matching(room.mobs().stream().map(v->v.id().toString()).toList(),args[4]);}if(args.length==4&&args[1].equals("room")&&args[2].equals("effect"))return matching(List.of("add","remove"),args[3]);if(args.length==5&&args[1].equals("room")&&args[2].equals("effect")&&args[3].equals("add"))return matching(List.of("both","mobs","players"),args[4]);if(args.length==6&&args[1].equals("room")&&args[2].equals("effect")&&args[3].equals("add"))return matching(effectNames(),args[5]);if(args.length==7&&args[1].equals("room")&&args[2].equals("effect")&&args[3].equals("add"))return matching(List.of("1","2","64","256"),args[6]);if(args.length==8&&args[1].equals("room")&&args[2].equals("effect")&&args[3].equals("add"))return matching(List.of("false","true"),args[7]);if(args.length==5&&args[1].equals("room")&&args[2].equals("effect")&&args[3].equals("remove")&&sender instanceof Player player){var room=controller.standingRoom(player).orElse(null);return room==null?List.of():matching(room.effects().stream().map(v->v.id().toString()).toList(),args[4]);}if(args.length==4&&args[1].equals("room")&&args[2].equals("boss"))return matching(List.of("assign-sheet","clear","mob"),args[3]);if(args.length==5&&args[1].equals("room")&&args[2].equals("boss")&&args[3].equals("mob"))return matching(entityNames(),args[4]);if(args.length==5&&args[1].equals("room")&&args[2].equals("boss")&&args[3].equals("assign-sheet"))return matching(List.of("0.1","1","1.5","10","100"),args[4]);return List.of();}
private List<Map.Entry<Player,org.bukkit.inventory.ItemStack>> authorizedPhysical(games.dmg.fantasystick.persistence.CharacterRecord character){return plugin.getServer().getOnlinePlayers().stream().flatMap(holder->Arrays.stream(holder.getInventory().getContents()).filter(Objects::nonNull).filter(item->sheets.authorizes(item,character)).map(item->Map.entry(holder,item))).toList();}
private static boolean ambiguousPhysical(List<Map.Entry<Player,org.bukkit.inventory.ItemStack>> physical,Player player){return physical.stream().mapToLong(entry->entry.getValue().getAmount()).sum()>1||physical.size()>1||physical.size()==1&&physical.getFirst().getKey()!=player;}
private long physicalCopies(UUID character){return plugin.getServer().getOnlinePlayers().stream().flatMap(holder->Arrays.stream(holder.getInventory().getContents())).filter(Objects::nonNull).filter(item->sheets.identify(item).filter(character::equals).isPresent()).mapToLong(org.bukkit.inventory.ItemStack::getAmount).sum();}
private boolean recoverable(UUID dungeon){var definition=directory.find(dungeon).orElse(null);var catalog=adventures.snapshot().catalog();return definition!=null&&!definition.enabled()&&directory.custodyForDungeon(dungeon).isPresent()&&!controller.beingEdited(dungeon)&&!controller.occupied(dungeon)&&(catalog==null||!adventures.offerOpen(dungeon))&&adventures.active().stream().noneMatch(quest->quest.site().equals(dungeon));}
private UUID editing(Player player){var result=controller.editing(player.getUniqueId()).orElse(null);if(result==null)player.sendMessage("Start editing one dungeon first.");return result;}
private DungeonState.Room standing(CommandSender sender,Player player){var result=controller.standingRoom(player).orElse(null);if(result==null)sender.sendMessage("Stand inside exactly one room of the dungeon being edited.");return result;}
private UUID editing(Player player){var result=controller.editing(player.getUniqueId()).orElse(null);if(result==null){refused("owner_refused");player.sendMessage("Start editing one dungeon first.");}return result;}
private DungeonState.Room standing(CommandSender sender,Player player){var result=controller.standingRoom(player).orElse(null);if(result==null){refused("owner_refused");sender.sendMessage("Stand inside exactly one room of the dungeon being edited.");}return result;}
private void saved(CommandSender sender,Throwable failure,String success){respond(sender,()->sender.sendMessage(failure==null?success:"Dungeon edit failed; desired state is unchanged."));}
private boolean authorized(CommandSender sender){if(sender.hasPermission(PERMISSION))return true;sender.sendMessage("Permission denied: you need fantasystick.admin to administer Fantasy Stick.");return false;}
private void respond(CommandSender sender,Runnable response){try{nextTick.accept(()->{if(sender.hasPermission(PERMISSION)&&(!(sender instanceof Player player)||player.isOnline()))response.run();});}catch(RuntimeException ignored){}}
@@ -69,5 +119,5 @@ public final class DungeonCommands {
private static String join(String[] args,int from){return from>=args.length?"":String.join(" ",Arrays.copyOfRange(args,from,args.length));}
private static List<String> matching(Collection<String> values,String prefix){return values.stream().filter(value->value.startsWith(prefix)).distinct().sorted().toList();}
private static List<String> modeValues(){return Arrays.stream(games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode.values()).map(games.dmg.fantasystick.adventure.AdventureQuestState.ParticipationMode::value).toList();}
private static void usage(CommandSender sender){sender.sendMessage("Usage: /fstickadmin dungeon <create [--mode <mode>] <name...>|mode <dungeon-uuid> [<mode>]|list|remove|edit|entrance|reward|room|boss|enable|disable|open|close|teleport> ...");}
private void usage(CommandSender sender){refused("invalid_arguments");sender.sendMessage("Usage: /fstickadmin dungeon <create [--mode <mode>] <name...>|mode <dungeon-uuid> [<mode>]|list|remove|edit|entrance|reward|room|boss|enable|disable|open|close|teleport> ...");}
}
@@ -54,7 +54,10 @@ public final class DungeonController implements Listener,AutoCloseable,games.dmg
private record PendingKill(UUID entity,UUID dungeon,UUID room,UUID generation,UUID slot,games.dmg.fantasystick.events.DungeonAuditEventBridge.RuntimeFacts observation){}
private static final class Attempt {final UUID dungeon,room,generation;final Map<UUID,UUID> entities=new HashMap<>();final Set<UUID> represented=new HashSet<>();final Map<UUID,Double> threat=new HashMap<>();final Map<String,Long> cooldowns=new HashMap<>();final Map<String,Long> effects=new HashMap<>();UUID boss,target,defeatedBoss;games.dmg.fantasystick.events.DungeonAuditEventBridge.RuntimeFacts observation,deathObservation;games.dmg.fantasystick.events.CharacterBossEventBridge.Facts characterDeathObservation;Map<String,String> defeatAudit=Map.of();long lastCombat=System.nanoTime();Attempt(UUID dungeon,UUID room,UUID generation){this.dungeon=dungeon;this.room=room;this.generation=generation;}}
private record Context(UUID character,UUID party,Set<UUID> members){}
private record OwnedEffect(UUID dungeon,UUID player,PotionEffectType type,int amplifier,PotionEffect prior,games.dmg.fantasystick.events.DungeonAuditEventBridge.RuntimeFacts observation){}
private record OwnedEffect(UUID dungeon,UUID definition,UUID player,PotionEffectType type,PotionEffect applied,PotionEffect prior,Integer priorTick,Integer appliedTick,games.dmg.fantasystick.events.DungeonAuditEventBridge.RuntimeFacts observation){}
private record PlayerRoomEffect(UUID dungeon,DungeonState.Room room,Player player,DungeonState.Effect definition,PotionEffectType type){}
private record RoomPotion(LivingEntity target,PotionEffectType type,List<EntityPotionEffectEvent> events){}
private final ThreadLocal<Deque<RoomPotion>> roomPotions=ThreadLocal.withInitial(ArrayDeque::new);
private final Plugin plugin;private final DungeonDirectory dungeons;private final AdventureQuestDirectory adventures;private final EquipmentSessions sessions;private final PartyRoster parties;private final CharacterStorage characters;private final ProgressionRules progression;private final Consumer<Runnable> nextTick;private final java.util.random.RandomGenerator random;private final AbilityRegistry abilities;private final PassiveRegistry passives;private final java.util.function.Supplier<games.dmg.fantasystick.session.OutOfCombatRecovery.Settings> recoverySettings;private final java.util.function.Function<games.dmg.fantasystick.persistence.CharacterRecord,BigInteger> recoveryBonus;private final java.util.function.Supplier<BigInteger> healthStealHealing;private final games.dmg.fantasystick.presentation.ParticleDelivery particles;private FishingController fishing;private games.dmg.fantasystick.events.DungeonEventBridge auditEvents;
private final NamespacedKey typeKey,dungeonKey,roomKey,slotKey,generationKey,bossKey;
private final Map<UUID,Edit> playerEdits=new HashMap<>();private final Map<UUID,UUID> dungeonEditors=new HashMap<>();private final Map<AttemptKey,Attempt> attempts=new HashMap<>();private final Set<String> startingRuns=new HashSet<>();private final Set<AttemptKey> completing=new HashSet<>();private final Set<UUID> defeatingDungeons=new HashSet<>();private final Set<CompletableFuture<?>> inFlight=ConcurrentHashMap.newKeySet();private final Map<String,OwnedEffect> ownedEffects=new HashMap<>();private final Map<UUID,PendingKill> pendingKills=new ConcurrentHashMap<>();private final Map<UUID,UUID> pendingBosses=new ConcurrentHashMap<>();private final Set<Entity> relocating=Collections.newSetFromMap(new IdentityHashMap<>());private org.bukkit.scheduler.BukkitTask pulse;private boolean closed;private long ticks=9;
@@ -107,7 +110,7 @@ public final class DungeonController implements Listener,AutoCloseable,games.dmg
private CompletionStage<Void> cleanupOnMain(UUID dungeon){var result=new CompletableFuture<Void>();if(closed){result.completeExceptionally(new IllegalStateException("Dungeon controller closed"));return result;}try{nextTick.accept(()->{if(closed){result.completeExceptionally(new IllegalStateException("Dungeon controller closed"));return;}cleanupDungeon(dungeon);synchronized(this){var editor=dungeonEditors.remove(dungeon);if(editor!=null)playerEdits.remove(editor);}result.complete(null);});}catch(RuntimeException failure){result.completeExceptionally(failure);}return result;}
public void definitionChanged(UUID dungeon){synchronized(this){var editor=dungeonEditors.get(dungeon);if(editor==null)return;var edit=playerEdits.get(editor);if(edit==null)return;for(var room:dungeons.find(dungeon).map(DungeonState.Dungeon::rooms).orElse(List.of()))edit.colors().computeIfAbsent(room.id(),ignored->randomColor());}}
private void tick(){if(closed)return;if(++ticks%10==0)showBorders();runtime();}
private void runtime(){var catalog=adventures.snapshot().catalog();if(catalog==null||adventures.snapshot().reset()!=null){cleanupRuntime();return;}var activeDungeonIds=catalog.sites().stream().filter(adventures::offerOpen).filter(id->adventures.findSite(id).map(AdventureQuestState.Site::type).orElse(null)==AdventureQuestState.SiteType.DUNGEON).collect(java.util.stream.Collectors.toSet());for(var key:new ArrayList<>(attempts.keySet()))if(!activeDungeonIds.contains(key.dungeon()))cleanupAttempt(key);var activeEffects=new HashSet<String>();for(UUID dungeonId:activeDungeonIds){if(defeatingDungeons.contains(dungeonId))continue;var dungeon=dungeons.find(dungeonId).orElse(null);if(dungeon==null)continue;var run=dungeons.runView(dungeonId,catalog.revision()).orElse(null);if(run==null){String key=dungeonId+":"+catalog.revision();if(startingRuns.add(key)){var observation=facts(dungeon,null,catalog.revision(),null,Map.of("reason","offered_runtime_initialized"));var source=dungeons.run(dungeonId,catalog.revision());source.whenComplete((ignored,failure)->{if(failure==null&&DungeonDirectory.publication(source).isPresent())observe("dungeon.run.started",observation,Map.of("run_status","persisted_undefeated"));schedule(()->startingRuns.remove(key));});}continue;}if(run.defeated()){cleanupDungeon(dungeonId);continue;}for(var room:dungeon.rooms()){var players=eligibleInside(dungeon,room).toList();var key=new AttemptKey(dungeonId,room.id());if(players.isEmpty()){cleanupAttempt(key,"no_eligible_player_in_room");continue;}applyPlayerEffects(dungeon.id(),room,players,activeEffects);if(run.clearedRooms().contains(room.id())){cleanupAttempt(key);continue;}if(completing.contains(key))continue;var attempt=attempts.computeIfAbsent(key,ignored->{var created=new Attempt(dungeonId,room.id(),catalog.revision());var trigger=players.getFirst();created.observation=facts(dungeon,room,catalog.revision(),trigger,questData(eligible(trigger,dungeonId)));observe("dungeon.room.activated",created.observation,Map.of("attempt_capture_quality","native_transient_not_persisted","reason","eligible_room_entry"));return created;});contain(dungeon,room,attempt);if(attempt.entities.isEmpty()&&attempt.boss==null)spawnRoom(dungeon,room,run,attempt);if(room.boss()!=null&&room.boss().character()!=null)driveCharacterBoss(dungeon,room,attempt,players);if(room.mobs().isEmpty()&&room.boss()==null){attempt.represented.addAll(players.stream().map(this::eligibleQuest).filter(Objects::nonNull).map(AdventureQuestState.Quest::id).toList());clearRoom(dungeon,room,attempt,false);}}}cleanupOwnedEffects(activeEffects);}
private void runtime(){var catalog=adventures.snapshot().catalog();if(catalog==null||adventures.snapshot().reset()!=null){cleanupRuntime();return;}var activeDungeonIds=catalog.sites().stream().filter(adventures::offerOpen).filter(id->adventures.findSite(id).map(AdventureQuestState.Site::type).orElse(null)==AdventureQuestState.SiteType.DUNGEON).collect(java.util.stream.Collectors.toSet());for(var key:new ArrayList<>(attempts.keySet()))if(!activeDungeonIds.contains(key.dungeon()))cleanupAttempt(key);var desiredEffects=desiredPlayerEffects(activeDungeonIds,catalog.revision());var activeEffects=new HashSet<String>();for(UUID dungeonId:activeDungeonIds){if(defeatingDungeons.contains(dungeonId))continue;var dungeon=dungeons.find(dungeonId).orElse(null);if(dungeon==null)continue;var run=dungeons.runView(dungeonId,catalog.revision()).orElse(null);if(run==null){String key=dungeonId+":"+catalog.revision();if(startingRuns.add(key)){var observation=facts(dungeon,null,catalog.revision(),null,Map.of("reason","offered_runtime_initialized"));var source=dungeons.run(dungeonId,catalog.revision());source.whenComplete((ignored,failure)->{if(failure==null&&DungeonDirectory.publication(source).isPresent())observe("dungeon.run.started",observation,Map.of("run_status","persisted_undefeated"));schedule(()->startingRuns.remove(key));});}continue;}if(run.defeated()){cleanupDungeon(dungeonId);continue;}for(var room:dungeon.rooms()){var players=eligibleInside(dungeon,room).toList();var key=new AttemptKey(dungeonId,room.id());if(players.isEmpty()){cleanupAttempt(key,"no_eligible_player_in_room");continue;}applyPlayerEffects(dungeon.id(),room,players,activeEffects,desiredEffects);if(run.clearedRooms().contains(room.id())){cleanupAttempt(key);continue;}if(completing.contains(key))continue;var attempt=attempts.computeIfAbsent(key,ignored->{var created=new Attempt(dungeonId,room.id(),catalog.revision());var trigger=players.getFirst();created.observation=facts(dungeon,room,catalog.revision(),trigger,questData(eligible(trigger,dungeonId)));observe("dungeon.room.activated",created.observation,Map.of("attempt_capture_quality","native_transient_not_persisted","reason","eligible_room_entry"));return created;});contain(dungeon,room,attempt);if(attempt.entities.isEmpty()&&attempt.boss==null)spawnRoom(dungeon,room,run,attempt);if(room.boss()!=null&&room.boss().character()!=null)driveCharacterBoss(dungeon,room,attempt,players);if(room.mobs().isEmpty()&&room.boss()==null){attempt.represented.addAll(players.stream().map(this::eligibleQuest).filter(Objects::nonNull).map(AdventureQuestState.Quest::id).toList());clearRoom(dungeon,room,attempt,false);}}}cleanupOwnedEffects(activeEffects);}
private Context context(Player player){var active=sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);if(active==null)return null;var record=sessions.currentRecord(active).orElse(null);if(record==null||record.dead())return null;var party=parties.partyOf(player.getUniqueId()).orElse(null);return party==null?new Context(record.id(),null,Set.of(record.id())):new Context(record.id(),party.id(),Set.copyOf(party.characters()));}
private AdventureQuestState.Quest eligibleQuest(Player player){var context=context(player);if(context==null)return null;var quest=adventures.activeFor(context.character(),context.party()).orElse(null);return quest!=null&&quest.snapshot().contains(context.character())?quest:null;}
private AdventureQuestState.Quest eligible(Player player,UUID dungeon){var quest=eligibleQuest(player);return quest!=null&&quest.site().equals(dungeon)?quest:null;}
@@ -162,10 +165,204 @@ public final class DungeonController implements Listener,AutoCloseable,games.dmg
private static List<Player> abilityVictims(AbilityDefinition definition,Mob boss,Player target,List<Player> eligible,double range){if(definition.id().equals("chain_lightning")){var result=new ArrayList<Player>();result.add(target);int maximum=1+definition.parameters().getOrDefault("additional-targets",java.math.BigDecimal.ZERO).intValue();double jump=definition.parameters().getOrDefault("jump-range",java.math.BigDecimal.valueOf(range)).doubleValue();Player current=target;while(result.size()<maximum){var origin=current;var next=eligible.stream().filter(player->!result.contains(player)&&origin.hasLineOfSight(player)&&origin.getLocation().distanceSquared(player.getLocation())<=jump*jump).min(Comparator.comparingDouble((Player player)->origin.getLocation().distanceSquared(player.getLocation())).thenComparing(player->player.getUniqueId().toString())).orElse(null);if(next==null)break;result.add(next);current=next;}return List.copyOf(result);}double radius=definition.parameters().getOrDefault("radius",java.math.BigDecimal.valueOf(range)).doubleValue();var center=definition.id().equals("meteor")?target:boss;return definition.targetPolicy()==AbilityDefinition.TargetPolicy.AREA?eligible.stream().filter(player->center.hasLineOfSight(player)&&center.getLocation().distanceSquared(player.getLocation())<=radius*radius).toList():List.of(target);}
private void applyMobEffects(LivingEntity mob,List<DungeonState.Effect> effects){for(var effect:effects)if(effect.target()!=DungeonState.EffectTarget.PLAYERS){var type=effectType(effect.effect());if(type!=null)mob.addPotionEffect(new PotionEffect(type,PotionEffect.INFINITE_DURATION,effect.level()-1,false,effect.particles()));}}
private final Set<String> observedEffectKeys=new HashSet<>();
private void applyPlayerEffects(UUID dungeon,DungeonState.Room room,List<Player> players,Set<String> active){for(var effect:room.effects())if(effect.target()!=DungeonState.EffectTarget.MOBS){var type=effectType(effect.effect());if(type==null)continue;for(var player:players){String key=player.getUniqueId()+":"+effect.id();active.add(key);var current=effect(player,type);int amplifier=effect.level()-1;if(current!=null&&current.getAmplifier()>amplifier)continue;var owned=ownedEffects.computeIfAbsent(key,ignored->new OwnedEffect(dungeon,player.getUniqueId(),type,amplifier,current,effectFacts(dungeon,room,player,effect)));player.addPotionEffect(new PotionEffect(type,30,amplifier,false,effect.particles()),true);if(ownerEvents!=null)try{var applied=effect(player,type);if(applied!=null&&applied.getAmplifier()==amplifier&&observedEffectKeys.add(key))observe("effect.applied",owned.observation(),Map.of("application_status","native_layer_confirmed","reason","eligible_room_effect"));}catch(RuntimeException unavailable){/* This optional confirmation cannot interrupt native application or room runtime. */}}}}
private Map<String,PlayerRoomEffect> desiredPlayerEffects(Set<UUID> activeDungeons,UUID generation){
var desired=new LinkedHashMap<String,PlayerRoomEffect>();
for(var dungeonId:activeDungeons){
if(defeatingDungeons.contains(dungeonId))continue;
var dungeon=dungeons.find(dungeonId).orElse(null);var run=dungeons.runView(dungeonId,generation).orElse(null);
if(dungeon==null||run==null||run.defeated())continue;
for(var room:dungeon.rooms())for(var player:eligibleInside(dungeon,room).toList())
for(var definition:room.effects())if(definition.target()!=DungeonState.EffectTarget.MOBS){
var type=effectType(definition.effect());if(type==null)continue;
String key=player.getUniqueId()+":"+type.getKey();var previous=desired.get(key);
// Native dominance: strongest level wins; the last equal-level definition supplies flags.
if(previous==null||definition.level()>=previous.definition().level())
desired.put(key,new PlayerRoomEffect(dungeonId,room,player,definition,type));
}
}
return desired;
}
private void applyPlayerEffects(UUID dungeon,DungeonState.Room room,List<Player> players,Set<String> active,Map<String,PlayerRoomEffect> desired){
for(var entry:desired.entrySet()){
var selected=entry.getValue();
if(!selected.dungeon().equals(dungeon)||!selected.room().id().equals(room.id())||!players.contains(selected.player()))continue;
var definition=selected.definition();var type=selected.type();var player=selected.player();
String key=entry.getKey();active.add(key);
var current=effect(player,type);var previous=ownedEffects.get(key);
if(previous!=null&&!sameOwnedLayer(current,previous,player)){
releaseRoomOwnership(key,previous,"unrelated_current_layer_preserved");previous=null;
}
int amplifier=definition.level()-1;
if(previous!=null&&!previous.definition().equals(definition.id())&&current.getAmplifier()>amplifier){
restoreOwned(key,previous);
if(ownedEffects.containsKey(key))continue; // Cancelled native removal retains its owned layer.
previous=null;current=effect(player,type);
}
if(current!=null&&current.getAmplifier()>amplifier)continue;
Integer priorTick=previous==null?nativeAge(player):previous.priorTick();
var requested=new PotionEffect(type,30,amplifier,false,definition.particles());
var call=new RoomPotion(player,type,new ArrayList<>());
boolean returned;
roomPotions.get().push(call);
try{returned=player.addPotionEffect(requested,true);}finally{finishRoomPotion(call);}
// Actual native return/final cancellation decision, never an equal-amplifier prior.
if(!returned||call.events().stream().anyMatch(event->event.isCancelled()
||event.getNewEffect()==null||!requested.equals(event.getNewEffect())
||event.getAction()==EntityPotionEffectEvent.Action.CHANGED&&!event.isOverride()))continue;
PotionEffect signature=roomSignature(requested,current);boolean verified=false;
try{
var applied=effect(player,type);
if(!confirmedRoomLayer(applied,requested,current))continue;
signature=applied;verified=true;
}catch(RuntimeException unavailable){
// A successful native call is still authoritative. Optional post-call metadata
// cannot undo it; cleanup requires its exact signature before any mutation.
}
boolean changed=previous!=null&&!previous.definition().equals(definition.id());
if(changed&&observedEffectKeys.remove(key))observe("effect.ended",previous.observation(),
Map.of("reason","owned_room_layer_released","cleanup_status","replaced_by_composed_room_layer"));
var owned=new OwnedEffect(dungeon,definition.id(),player.getUniqueId(),type,signature,
previous==null?current:previous.prior(),priorTick,nativeAge(player),
previous==null||changed?effectFacts(dungeon,room,player,definition):previous.observation());
ownedEffects.put(key,owned);
if(verified&&ownerEvents!=null&&observedEffectKeys.add(key))
observe("effect.applied",owned.observation(),Map.of("application_status","native_layer_confirmed","reason","eligible_room_effect"));
}
}
private static Integer nativeAge(Player player){try{return player.getTicksLived();}catch(RuntimeException unavailable){return null;}}
private static PotionEffect remainingPrior(PotionEffect prior,long elapsed){
if(prior==null)return null;
var hidden=remainingPrior(prior.getHiddenPotionEffect(),elapsed);
if(!prior.isInfinite()&&prior.getDuration()<=elapsed)return hidden;
int duration=prior.isInfinite()?PotionEffect.INFINITE_DURATION:(int)(prior.getDuration()-elapsed);
return new PotionEffect(prior.getType(),duration,prior.getAmplifier(),prior.isAmbient(),prior.hasParticles(),prior.hasIcon(),hidden);
}
private void cleanupOwnedEffects(Set<String> active){for(var entry:new ArrayList<>(ownedEffects.entrySet()))if(!active.contains(entry.getKey()))restoreOwned(entry.getKey(),entry.getValue());}
private void cleanupOwnedDungeon(UUID dungeon){for(var entry:new ArrayList<>(ownedEffects.entrySet()))if(entry.getValue().dungeon().equals(dungeon))restoreOwned(entry.getKey(),entry.getValue());}
private void restoreOwned(String key,OwnedEffect owned){ownedEffects.remove(key);boolean observed=observedEffectKeys.remove(key);var player=plugin.getServer().getPlayer(owned.player());if(player==null){if(observed)observe("effect.ended",owned.observation(),Map.of("reason","owned_room_layer_released","cleanup_status","player_unavailable"));return;}var current=effect(player,owned.type());if(current!=null&&current.getAmplifier()==owned.amplifier()){player.removePotionEffect(owned.type());if(owned.prior()!=null&&owned.prior().getDuration()>0)player.addPotionEffect(owned.prior(),true);if(observed)observe("effect.ended",owned.observation(),Map.of("reason","owned_room_layer_released","cleanup_status","native_restore_returned","prior_layer_status",owned.prior()==null?"absent":"restored_request"));}else if(observed)observe("effect.ended",owned.observation(),Map.of("reason","owned_room_layer_released","cleanup_status","unrelated_current_layer_preserved"));}
private void restoreOwned(String key,OwnedEffect owned){
var player=plugin.getServer().getPlayer(owned.player());
if(player==null){releaseRoomOwnership(key,owned,"player_unavailable");return;}
var current=effect(player,owned.type());
if(!sameOwnedLayer(current,owned,player)){
releaseRoomOwnership(key,owned,"unrelated_current_layer_preserved");return;
}
var call=new RoomPotion(player,owned.type(),new ArrayList<>());
roomPotions.get().push(call);
try{player.removePotionEffect(owned.type());}finally{finishRoomPotion(call);}
var remaining=effect(player,owned.type());
if(sameOwnedLayer(remaining,owned,player)){
// A cancelled native removal cannot justify restoring a prior or asserting an end.
// Cancellation retains the lease; only confirmed removal may emit the supported effect.ended.
return;
}
if(remaining!=null){releaseRoomOwnership(key,owned,"unrelated_current_layer_preserved");return;}
String priorStatus=owned.prior()==null?"absent":"expired";
var now=nativeAge(player);PotionEffect prior=null;
if(owned.prior()!=null){
if(now!=null&&owned.priorTick()!=null)
prior=remainingPrior(owned.prior(),Integer.toUnsignedLong(now-owned.priorTick()));
else priorStatus="remaining_lifetime_unavailable"; // Never invent a remaining native budget.
}
if(prior!=null){
boolean accepted=restorePriorChain(player,prior);
priorStatus=accepted&&sameRoomLayer(effect(player,owned.type()),prior)?"restored_request":"restore_unconfirmed";
}
ownedEffects.remove(key);boolean observed=observedEffectKeys.remove(key);
if(observed)observe("effect.ended",owned.observation(),Map.of("reason","owned_room_layer_released",
"cleanup_status","native_restore_returned","prior_layer_status",priorStatus));
}
private boolean restorePriorChain(Player player,PotionEffect prior){
var layers=new ArrayList<PotionEffect>();
for(var layer=prior;layer!=null;layer=layer.getHiddenPotionEffect())layers.add(layer);
// Bukkit input conversion drops hidden nodes: let actual native merges rebuild deepest first.
for(int index=layers.size()-1;index>=0;index--){
var layer=layers.get(index);
var requested=new PotionEffect(layer.getType(),layer.getDuration(),layer.getAmplifier(),layer.isAmbient(),layer.hasParticles(),layer.hasIcon());
if(index<layers.size()-1){
var lower=layers.get(index+1);
if(requested.isInfinite()||!lower.isInfinite()&&requested.getDuration()>=lower.getDuration()){
// A longer/infinite stronger addition would discard lower state. Hide it with a
// short visible-only seed first, then extend without resetting any lower budget.
int seedDuration=lower.isInfinite()?1:Math.min(1,lower.getDuration()-1);
if(!restorePriorLayer(player,requested.withDuration(seedDuration)))return false;
}
}
if(!restorePriorLayer(player,requested))return false;
}
return true;
}
private boolean restorePriorLayer(Player player,PotionEffect requested){
var call=new RoomPotion(player,requested.getType(),new ArrayList<>());boolean accepted;
roomPotions.get().push(call);
try{accepted=player.addPotionEffect(requested,true);}finally{finishRoomPotion(call);}
return accepted&&call.events().stream().noneMatch(event->event.isCancelled()||event.getNewEffect()==null
||!requested.equals(event.getNewEffect())
||event.getAction()==EntityPotionEffectEvent.Action.CHANGED&&!event.isOverride());
}
private void finishRoomPotion(RoomPotion call){
var stack=roomPotions.get();stack.remove(call);if(stack.isEmpty())roomPotions.remove();
}
private static PotionEffect roomSignature(PotionEffect requested,PotionEffect prior){
int duration=requested.getDuration();var hidden=prior==null?null:prior.getHiddenPotionEffect();
if(prior!=null){
if(prior.getAmplifier()==requested.getAmplifier())
duration=prior.isInfinite()?PotionEffect.INFINITE_DURATION:Math.max(prior.getDuration(),duration);
else if(requested.getAmplifier()>prior.getAmplifier()&&!requested.isInfinite()
&&(prior.isInfinite()||requested.getDuration()<prior.getDuration()))hidden=prior;
}
// Only the hidden state dictated by the captured prior/native merge is admissible.
return new PotionEffect(requested.getType(),duration,requested.getAmplifier(),requested.isAmbient(),requested.hasParticles(),requested.hasIcon(),hidden);
}
private static boolean confirmedRoomLayer(PotionEffect applied,PotionEffect requested,PotionEffect prior){
return sameRoomLayer(applied,roomSignature(requested,prior));
}
private static boolean sameOwnedLayer(PotionEffect current,OwnedEffect owned,Player player){
var signature=owned.applied();
if(signature.getHiddenPotionEffect()==null)return sameRoomLayer(current,signature);
var now=nativeAge(player);
if(now==null||owned.appliedTick()==null)return false;
long elapsed=Integer.toUnsignedLong(now-owned.appliedTick());
if(!signature.isInfinite()&&signature.getDuration()<=elapsed)return false; // A promoted prior is never our visible layer.
return sameRoomLayer(current,decayedNativeSignature(signature,elapsed));
}
private static PotionEffect decayedNativeSignature(PotionEffect signature,long elapsed){
if(signature==null)return null;
int duration=signature.isInfinite()?PotionEffect.INFINITE_DURATION:(int)Math.max(0,signature.getDuration()-elapsed);
// Native hidden nodes remain structurally present at zero until the visible layer downgrades.
return new PotionEffect(signature.getType(),duration,signature.getAmplifier(),signature.isAmbient(),
signature.hasParticles(),signature.hasIcon(),decayedNativeSignature(signature.getHiddenPotionEffect(),elapsed));
}
private static boolean sameRoomLayer(PotionEffect current,PotionEffect signature){
if(current==null)return false;
boolean duration=signature.isInfinite()?current.isInfinite()
:current.getDuration()>0&&current.getDuration()<=signature.getDuration();
// withDuration drops Paper's hidden chain; explicitly retain every matching field/layer.
return duration&&new PotionEffect(signature.getType(),current.getDuration(),signature.getAmplifier(),
signature.isAmbient(),signature.hasParticles(),signature.hasIcon(),signature.getHiddenPotionEffect()).equals(current);
}
private void releaseRoomOwnership(String key,OwnedEffect owned,String status){
ownedEffects.remove(key);
if(observedEffectKeys.remove(key))observe("effect.ended",owned.observation(),
Map.of("reason","owned_room_layer_released","cleanup_status",status));
}
@EventHandler(priority=EventPriority.MONITOR)
public void roomPotionChanged(EntityPotionEffectEvent event){
var call=roomPotions.get().peek();
if(call!=null&&call.target()==event.getEntity()&&call.type().equals(event.getModifiedType())){
call.events().add(event);return;
}
if(call==null)roomPotions.remove();
if(event.isCancelled()||!(event.getEntity() instanceof Player player)
||event.getAction()==EntityPotionEffectEvent.Action.CHANGED&&!event.isOverride()
||event.getAction()==EntityPotionEffectEvent.Action.ADDED)return;
// Accepted unscoped native changes revoke the lease even if every visible field is equal.
for(var entry:new ArrayList<>(ownedEffects.entrySet())){
var owned=entry.getValue();
if(owned.player().equals(player.getUniqueId())&&owned.type().equals(event.getModifiedType()))
releaseRoomOwnership(entry.getKey(),owned,"unrelated_current_layer_preserved");
}
}
private static PotionEffect effect(LivingEntity entity,PotionEffectType type){return entity.getActivePotionEffects().stream().filter(value->value.getType().equals(type)).findFirst().orElse(null);}
private static PotionEffectType effectType(String key){var value=NamespacedKey.fromString(key);return value==null?null:PotionEffectType.getByKey(value);}
private void contain(DungeonState.Dungeon dungeon,DungeonState.Room room,Attempt attempt){var world=plugin.getServer().getWorld(dungeon.world());if(world==null)return;for(var entity:safe(world.getEntities()))if(managed(entity)&&dungeon.id().equals(id(entity,dungeonKey))&&room.id().equals(id(entity,roomKey))&&!inside(entity.getLocation(),dungeon,room)){relocating.add(entity);try{entity.teleport(new Location(world,(room.bounds().minX()+room.bounds().maxX()+1)/2d,room.bounds().minY()+1,(room.bounds().minZ()+room.bounds().maxZ()+1)/2d));if(entity instanceof LivingEntity living)living.setVelocity(new org.bukkit.util.Vector());}finally{relocating.remove(entity);}}}
@@ -33,14 +33,22 @@ public final class AbilityConfigEventBridge {
}
public void read(Actor actor, String abilityId, String key, String value) {
emit("config.read", actor, abilityId, key, null, value);
read(UUID.randomUUID(), actor, abilityId, key, value);
}
public void read(UUID operation, Actor actor, String abilityId, String key, String value) {
emit(operation, "config.read", actor, abilityId, key, null, value);
}
public void changed(Actor actor, String abilityId, String key, String before, String after) {
emit("config.changed", actor, abilityId, key, before, after);
changed(UUID.randomUUID(), actor, abilityId, key, before, after);
}
private void emit(String type, Actor actor, String abilityId, String key, String before, String after) {
public void changed(UUID operation, Actor actor, String abilityId, String key, String before, String after) {
emit(operation, "config.changed", actor, abilityId, key, before, after);
}
private void emit(UUID operation, String type, Actor actor, String abilityId, String key, String before, String after) {
try {
var data = new LinkedHashMap<String, Object>();
data.put("actor_kind", actor.kind());
@@ -50,12 +58,11 @@ public final class AbilityConfigEventBridge {
data.put("after", after);
data.put("application", "future_casts_only");
data.put("outcome", "acknowledged");
var action = UUID.randomUUID();
var id = UUID.nameUUIDFromBytes(("fantasystick:ability-config:" + action + ":" + type)
var id = UUID.nameUUIDFromBytes(("fantasystick:ability-config:" + operation + ":" + type)
.getBytes(StandardCharsets.UTF_8));
var context = actor.playerId() == null ? null
: new EventInput.Context(actor.playerId(), actor.playerName(), null, null, null, null);
sink.accept(new EventInput(id, action, clock.instant(), type, context, data));
sink.accept(new EventInput(id, operation, clock.instant(), type, context, data));
} catch (RuntimeException ignored) { /* File logging cannot change an authorized configuration action. */ }
}
}
@@ -0,0 +1,313 @@
package games.dmg.fantasystick.events;
import games.dmg.fantasystick.session.EquipmentSessions;
import java.nio.file.Path;
import java.time.Clock;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Function;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/** Captured command-entry audit. Outcomes are supplied by the authoritative owner, never parsed from feedback. */
public final class AdminActionEventBridge implements AutoCloseable {
private static final Set<String> ROUTES = Set.of("adventure", "adventure-site", "quest-giver",
"character", "dungeon", "shop", "rare-shop", "training-dummy", "party-registrar",
"config", "give", "revive", "experience", "inspect", "recover");
private static final Set<String> REASONS = Set.of("invalid_arguments", "unauthorized", "owner_outcome_pending",
"native_entry_cancelled_at_observation", "native_entry_unauthorized_at_observation",
"sender_unsupported", "stale", "not_found", "no_change", "confirmation_required",
"permission_changed", "operation_failed", "operation_uncertain", "acknowledged",
"read_completed", "owner_refused", "owner_pending");
private static final Set<String> FACTS = Set.of("domain_operation_id", "domain_event_id", "subject_id",
"target_id", "before", "after", "amount", "key", "setting", "revision_before",
"revision_after", "confirmation", "requested", "applied");
public enum Outcome { COMPLETED, REFUSED, FAILED, PENDING, UNCERTAIN }
/** Contains only captured immutable facts; never a sender, live session, command or argument array. */
public static final class Action {
private final UUID id;
private final String route, actorKind, authorization;
private final EventInput.Context context;
private final Map<String, Object> location;
private final Map<String, Object> arguments;
private final boolean invalidShape;
private boolean terminal, pending;
private Action(UUID id, String route, String actorKind, String authorization,
EventInput.Context context, Map<String, Object> location,
Map<String, Object> arguments, boolean invalidShape) {
this.id = id; this.route = route; this.actorKind = actorKind; this.authorization = authorization;
this.context = context; this.location = location; this.arguments = arguments;
this.invalidShape = invalidShape;
}
public UUID id() { return id; }
public String route() { return route; }
public boolean authorized() { return authorization.equals("authorized"); }
}
/** Restores the previous same-thread scope even on exceptions or nested command dispatch. */
public final class Invocation implements AutoCloseable {
private final Action action;
private final Action previous;
private boolean closed;
private Invocation(Action action) {
this.action = action;
previous = active.get();
active.set(action);
}
public Action action() { return action; }
@Override public void close() {
if (closed) return;
closed = true;
try {
synchronized (action) {
if (!action.terminal && !action.pending) {
if (!action.authorized()) result(action, Outcome.REFUSED, "unauthorized", Map.of());
else if (action.invalidShape) result(action, Outcome.REFUSED, "invalid_arguments", Map.of());
else result(action, Outcome.PENDING, "owner_outcome_pending", Map.of());
}
}
} finally {
if (previous == null) active.remove(); else active.set(previous);
}
}
}
private final Clock clock;
private final EquipmentSessions sessions;
private final FeatureEventOutbox outbox;
private final ThreadLocal<Action> active = new ThreadLocal<>();
private final java.util.concurrent.atomic.AtomicBoolean closed = new java.util.concurrent.atomic.AtomicBoolean();
private final Set<String> configurationKeys = java.util.concurrent.ConcurrentHashMap.newKeySet();
public void allowConfigurationKeys(java.util.Collection<String> keys) {
// Supplied by the existing installed typed command catalog, never discovered through I/O/completion.
configurationKeys.addAll(keys);
}
// Diagnostic ownership only; async callers retain their own captured Action. Eviction cannot refuse gameplay.
private final Map<UUID, Action> recent = new LinkedHashMap<>(128, .75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<UUID, Action> eldest) { return size() > 1024; }
};
public AdminActionEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
Clock clock, Path data, EquipmentSessions sessions,
Consumer<Throwable> failures) {
this.clock = Objects.requireNonNull(clock);
this.sessions = Objects.requireNonNull(sessions);
outbox = new FeatureEventOutbox(data, "admin-action-event-intents", Set.of("admin.action"),
Objects.requireNonNull(sink), Objects.requireNonNull(failures));
}
public Action current() { return active.get(); }
public Invocation open(CommandSender sender, Command command, String label, String[] args) {
Objects.requireNonNull(sender);
Objects.requireNonNull(command);
// The caller is the registered executor; neither label spelling nor argument text is an audit identity.
var action = capture(sender, args);
emit(action, "request", null, null, Map.of());
emit(action, "authorization", null, null, Map.of());
return new Invocation(action);
}
/** Only for a final native entry observation where the plugin executor will not run. */
public void nativeEntryRefused(CommandSender sender, String[] args, String reason) {
var action = capture(sender, args);
emit(action, "request", null, null, Map.of());
emit(action, "authorization", null, null, Map.of());
result(action, Outcome.REFUSED, reason, Map.of());
}
private Action capture(CommandSender sender, String[] args) {
boolean permitted = sender.hasPermission("fantasystick.admin");
String route = args != null && args.length > 0 && ROUTES.contains(args[0]) ? args[0] : "unknown";
var player = sender instanceof Player value ? value : null;
String kind = player != null ? "player" : sender instanceof BlockCommandSender ? "command_block" : "console";
EventInput.Context context = null;
Map<String, Object> place = Map.of();
if (player != null) {
var id = player.getUniqueId();
UUID character = null, session = null;
String name = null;
try {
var current = sessions.active(id).orElse(null);
var record = current == null ? null : sessions.currentRecord(current).orElse(null);
if (record != null) { character = record.id(); name = record.name(); session = current.session(); }
} catch (RuntimeException unavailable) { /* Never turn missing session evidence into guessed identity. */ }
EventInput.Location physical = null;
try { physical = location(player.getLocation()); } catch (RuntimeException unavailable) { /* Optional native port. */ }
context = new EventInput.Context(id, player.getName(), character, name, session, physical);
} else if (sender instanceof BlockCommandSender block) {
try { place = locationData(block.getBlock().getLocation()); }
catch (RuntimeException unavailable) { /* Missing native location is not a player location. */ }
}
boolean valid = recognizedShape(route, args);
Map<String, Object> safeArgs = Map.of();
if (permitted && valid && (route.equals("inspect") || route.equals("recover"))) {
safeArgs = Map.of("player_id", UUID.fromString(args[1]).toString());
} else if (permitted && valid && route.equals("config")
&& configurationKeys.contains(args[1])) {
var typed = new LinkedHashMap<String, Object>();
typed.put("key", args[1]);
if (args.length == 3) {
var value = safeSettingValue(args[1], args[2]);
if (value != null) typed.put("value", value);
else typed.put("value_redacted", true);
}
safeArgs = Map.copyOf(typed);
}
var action = new Action(UUID.randomUUID(), route, kind, permitted ? "authorized" : "denied",
context, place, safeArgs, !valid);
synchronized (recent) { recent.put(action.id, action); }
return action;
}
private boolean recognizedShape(String route, String[] args) {
if (route.equals("unknown") || args == null) return false;
int length = args.length;
if (route.equals("inspect") || route.equals("recover")) {
if (length != 2) return false;
try { return UUID.fromString(args[1]).toString().equalsIgnoreCase(args[1]); }
catch (IllegalArgumentException invalid) { return false; }
}
if (route.equals("give") || route.equals("revive")) return length == 2;
if (route.equals("config")) return length == 2 || length == 3;
if (route.equals("experience")) return length >= 4 && args[1].equals("give");
if (route.equals("adventure")) return (length == 2 || length == 3)
&& args[1].equals("reroll") && (length == 2 || args[2].equals("confirm"));
if (length < 2) return false;
return switch (route) {
case "character" -> Set.of("find", "show", "recover", "view").contains(args[1]);
case "adventure-site" -> Set.of("list", "place", "fishing", "mode", "remove", "teleport").contains(args[1]);
case "quest-giver", "training-dummy", "party-registrar" -> Set.of("list", "place", "remove").contains(args[1]);
case "shop", "rare-shop" -> Set.of("list", "place", "remove", "restock").contains(args[1]);
case "dungeon" -> Set.of("create", "list", "mode", "remove", "edit", "entrance", "room",
"reward", "boss", "teleport", "enable", "disable", "open", "close").contains(args[1]);
default -> true;
};
}
public void result(Action action, Outcome outcome, String safeReason, Map<String, Object> typedFacts) {
if (action == null || outcome == null || closed.get()) return;
synchronized (action) {
if (action.terminal || outcome == Outcome.PENDING && action.pending) return;
var reason = REASONS.contains(safeReason) ? safeReason : "owner_refused";
var facts = action.authorized() && !action.route.equals("unknown") ? safeFacts(typedFacts) : Map.<String, Object>of();
emit(action, "result", outcome.name().toLowerCase(java.util.Locale.ROOT), reason, facts);
if (outcome == Outcome.PENDING) action.pending = true;
else { action.terminal = true; synchronized (recent) { recent.remove(action.id); } }
}
}
private Map<String, Object> safeFacts(Map<String, Object> input) {
if (input == null || input.isEmpty()) return Map.of();
var result = new LinkedHashMap<String, Object>();
input.forEach((key, value) -> {
if (!FACTS.contains(key)) return;
if (value instanceof UUID id) result.put(key, id.toString());
else if (value instanceof Boolean || value instanceof Integer) result.put(key, value);
else if (value instanceof Long number && number >= Integer.MIN_VALUE && number <= Integer.MAX_VALUE)
result.put(key, number.intValue());
else if (value instanceof String text && text.length() <= 2048) {
if (key.endsWith("_id")) {
try { result.put(key, UUID.fromString(text).toString()); } catch (IllegalArgumentException ignored) { }
} else if (key.equals("key") || key.equals("setting")) {
if (configurationKeys.contains(text)) result.put(key, text);
} else if (Set.of("true", "false", "on", "off", "confirm").contains(text)) result.put(key, text);
else {
boolean secretSetting = input.get("key") instanceof String setting
&& (setting.contains("url") || setting.contains("sha1") || setting.contains("hash")
|| setting.contains("password") || setting.contains("token"));
var number = secretSetting ? null : safeNumber(text);
if (number != null) result.put(key, number);
}
}
});
return Map.copyOf(result);
}
private static String safeSettingValue(String key, String value) {
if (key.contains("url") || key.contains("sha1") || key.contains("hash")
|| key.contains("password") || key.contains("token")) return null;
if (value.equals("true") || value.equals("false")) return value;
return safeNumber(value);
}
/** An intentional native confirmation, never a render, inert slot or a new gameplay authorization. */
public void confirmation(Action action, boolean permitted, String entryPoint, UUID causation) {
if (action == null || closed.get()) return;
if (!Set.of("inventory_confirmation", "command_confirmation").contains(entryPoint)) return;
synchronized (action) {
if (action.terminal) return;
var facts = new LinkedHashMap<String, Object>();
facts.put("confirmation", true);
facts.put("entry_point", entryPoint);
facts.put("authorization", permitted ? "authorized" : "denied");
if (causation != null) facts.put("causation_id", causation.toString());
emit(action, "confirmation", null, null, facts);
}
}
private static String safeNumber(String value) {
// Bounded typed decimal only: never free-form text, an URL, secret or nonfinite native value.
if (value.length() > 2048 || !value.matches("-?[0-9]+(?:\\.[0-9]+)?")) return null;
try { return new java.math.BigDecimal(value).stripTrailingZeros().toPlainString(); }
catch (NumberFormatException invalid) { return null; }
}
private void emit(Action action, String stage, String outcome, String reason, Map<String, Object> facts) {
try {
var data = new LinkedHashMap<String, Object>();
data.put("stage", stage);
data.put("route", action.route);
data.put("entry_point", "command");
data.put("actor_kind", action.actorKind);
data.put("authorization", action.authorization);
if (action.context == null) data.put("location_status", action.actorKind.equals("command_block")
? action.location.isEmpty() ? "unavailable" : "captured" : "not_applicable");
else if (action.context.location() == null) data.put("location_status", "unavailable");
if (!action.location.isEmpty()) data.put("location", action.location);
if (!action.arguments.isEmpty() && !"denied".equals(facts.get("authorization"))) data.put("arguments", action.arguments);
if (outcome != null) data.put("outcome", outcome);
if (reason != null) data.put("reason", reason);
data.putAll(facts);
outbox.accepted(new EventInput(UUID.randomUUID(), action.id, clock.instant(), "admin.action", action.context, data));
} catch (RuntimeException ignored) { /* Never let an audit failure authorize or reject a command. */ }
}
private EventInput.Location location(Location place) {
try {
if (place == null || place.getWorld() == null) return null;
return new EventInput.Location(place.getWorld().getUID(), place.getWorld().getName(),
place.getX(), place.getY(), place.getZ(), clock.instant(), "exact");
} catch (RuntimeException unavailable) { return null; }
}
private Map<String, Object> locationData(Location place) {
var captured = location(place);
if (captured == null) return Map.of();
return Map.of("world_id", captured.worldId().toString(), "world_name", captured.worldName(),
"x", captured.x(), "y", captured.y(), "z", captured.z(),
"captured_at", captured.capturedAt().toString(), "quality", captured.quality());
}
public void replay() { outbox.replay(); }
public CompletionStage<Void> drained() { return outbox.drained(); }
@Override public void close() {
if (closed.get()) return;
active.remove();
java.util.List<Action> pending;
synchronized (recent) { pending = java.util.List.copyOf(recent.values()); }
// Audit-only uncertainty at the owner lifetime boundary; never cancel/replay the domain operation.
for (var action : pending) result(action, Outcome.UNCERTAIN, "operation_uncertain", Map.of());
closed.set(true);
synchronized (recent) { recent.clear(); }
outbox.close();
}
}
@@ -0,0 +1,35 @@
package games.dmg.fantasystick.events;
import java.util.Objects;
import org.bukkit.command.PluginCommand;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.purpurmc.purpur.event.ExecuteCommandEvent;
/** Final native command-map observation, before PluginCommand's metadata permission check. */
public final class AdminCommandEntryObserver implements Listener {
private final PluginCommand root;
private final AdminActionEventBridge audit;
public AdminCommandEntryObserver(PluginCommand root, AdminActionEventBridge audit) {
this.root = Objects.requireNonNull(root);
this.audit = Objects.requireNonNull(audit);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public void observe(ExecuteCommandEvent event) {
// Object identity matters: another plugin's command/alias is never Fantasy Stick administration.
if (event.getCommand() != root) return;
try {
var sender = event.getSender();
boolean allowed = sender.hasPermission("fantasystick.admin");
if (!allowed || event.isCancelled()) {
// Describes only the state at this observation, not a claim about later monitor listeners.
audit.nativeEntryRefused(sender, event.getArgs(), allowed
? "native_entry_cancelled_at_observation" : "native_entry_unauthorized_at_observation");
}
// Otherwise the executor owns the request; observing here too would duplicate the action.
} catch (RuntimeException unavailable) { /* Audit may not change native dispatch or authority. */ }
}
}
@@ -124,21 +124,29 @@ public final class AdminRevivalEventBridge implements AutoCloseable {
}
public void read(Actor actor, String effective) {
read(UUID.randomUUID(), actor, effective);
}
public void read(UUID operation, Actor actor, String effective) {
if (actor == null) return;
var data = config(actor);
data.put("effective", effective);
data.put("outcome", "acknowledged_read");
emit(UUID.randomUUID(), "config.read", actor.context(), data);
emit(operation, "config.read", actor.context(), data);
}
public void changed(Actor actor, String before, AdminReviveSettings.Update saved) {
changed(UUID.randomUUID(), actor, before, saved);
}
public void changed(UUID operation, Actor actor, String before, AdminReviveSettings.Update saved) {
if (actor == null) return;
var data = config(actor);
data.put("before", before);
data.put("after", saved.value());
data.put("effective", saved.value());
data.put("outcome", "acknowledged");
durable("config.changed", UUID.randomUUID(), actor.context(), data);
durable("config.changed", operation, actor.context(), data);
}
private static Map<String, Object> config(Actor actor) {
@@ -140,14 +140,20 @@ public final class ArmorEventBridge implements AutoCloseable {
}
public void configRead(Actor actor, String key, String value) {
configuration("config.read", actor, key, null, value);
configuration("config.read", UUID.randomUUID(), actor, key, null, value);
}
public void configChanged(Actor actor, String key, String before, String after) {
configuration("config.changed", actor, key, before, after);
configuration("config.changed", UUID.randomUUID(), actor, key, before, after);
}
private void configuration(String type, Actor actor, String key, String before, String after) {
public void configRead(UUID operation, Actor actor, String key, String value) {
configuration("config.read", operation, actor, key, null, value);
}
public void configChanged(UUID operation, Actor actor, String key, String before, String after) {
configuration("config.changed", operation, actor, key, before, after);
}
private void configuration(String type, UUID operation, Actor actor, String key, String before, String after) {
try {
var operation = UUID.randomUUID(); var values = new LinkedHashMap<String, Object>();
var values = new LinkedHashMap<String, Object>();
actorData(values, actor); values.put("key", key); values.put("after", after);
if (before != null) values.put("before", before);
values.put("application", "next_armor_restock"); values.put("application_scope", "next_catalog");
@@ -161,9 +161,13 @@ public final class CampEventBridge implements AutoCloseable {
default->throw new IllegalArgumentException("Not a camp/catalog setting");};}
private static LinkedHashMap<String,Object> settingData(String key,String defaults){var data=new LinkedHashMap<String,Object>();
data.put("key",key);data.put("default",defaults);data.put("feature","camp_catalog");data.put("application_scope",settingScope(key));return data;}
public void configRead(Actor actor,String key,String effective,String defaults){
public void configRead(Actor actor,String key,String effective,String defaults) {
configRead(UUID.randomUUID(), actor, key, effective, defaults);
}
public void configRead(UUID operation, Actor actor,String key,String effective,String defaults) {
try{if(!ownsSetting(key))return;var data=settingData(key,defaults);data.put("effective",effective);data.put("outcome","acknowledged_read");
accepted("config.read",UUID.randomUUID(),actor,data);}catch(RuntimeException ignored){/* Reporting cannot depend on audit. */}
accepted("config.read",operation,actor,data);}catch(RuntimeException ignored){/* Reporting cannot depend on audit. */}
}
public void configChanged(Actor actor,UUID operation,String key,String before,String after,String defaults){
try{if(!ownsSetting(key)||before.equals(after))return;var data=settingData(key,defaults);data.put("before",before);data.put("after",after);
@@ -64,9 +64,13 @@ public final class ChampionEventBridge implements AutoCloseable {
data.put("application_scope",key.equals(games.dmg.fantasystick.persistence.AdventureQuestSettings.CHAMPION_HEALTH)
||key.equals(games.dmg.fantasystick.persistence.AdventureQuestSettings.CHAMPION_DAMAGE)?"future_attempts":"future_acceptances");return data;
}
public void configRead(CampEventBridge.Actor actor,String key,String effective,String defaults){
public void configRead(CampEventBridge.Actor actor,String key,String effective,String defaults) {
configRead(UUID.randomUUID(), actor, key, effective, defaults);
}
public void configRead(UUID operation, CampEventBridge.Actor actor,String key,String effective,String defaults) {
try{if(!ownsSetting(key))return;var data=settingData(key,defaults);data.put("effective",effective);data.put("outcome","acknowledged_read");
accepted("config.read",UUID.randomUUID(),actor,data);}catch(RuntimeException ignored){/* Reporting cannot depend on audit. */}
accepted("config.read",operation,actor,data);}catch(RuntimeException ignored){/* Reporting cannot depend on audit. */}
}
public void configChanged(CampEventBridge.Actor actor,UUID operation,String key,String before,String after,String defaults){
try{if(!ownsSetting(key)||before.equals(after))return;var data=settingData(key,defaults);data.put("before",before);data.put("after",after);
@@ -27,9 +27,11 @@ public final class CoinEventBridge implements AutoCloseable {
private void publish(EventInput event){if(outbox!=null)outbox.accepted(event);else sink.accept(event);}
public void initialized(CharacterRecord record,String source,CoinRules rules){var operation=stable(record.id(),"coins-initialized");var data=new LinkedHashMap<String,Object>();data.put("operation_id",operation.toString());data.put("character_id",record.id().toString());data.put("character_name",record.name());data.put("source",source);data.put("configured_minimum",Long.toString(rules.startingMin()));data.put("configured_maximum",Long.toString(rules.startingMax()));data.put("balance",record.coins().toString());data.put("revision",record.revision().toString());data.put("outcome","acknowledged");emit(operation,"character.coins_initialized",data);}
public void lost(CharacterRecord before,CharacterRecord after,UUID death,Instant diedAt){var data=new LinkedHashMap<String,Object>();data.put("operation_id",death.toString());data.put("death_id",death.toString());data.put("character_id",after.id().toString());data.put("character_name",after.name());data.put("reason","player_attributed_final_death");data.put("balance_before",before.coins().toString());data.put("balance_after",after.coins().toString());data.put("death_bound_escrow",after.pvpCoinEscrow().toString());data.put("before_revision",before.revision().toString());data.put("after_revision",after.revision().toString());data.put("final_death_at",diedAt.toString());data.put("outcome","acknowledged");emit(death,"character.coins_lost",data);}
public void configRead(String actorKind,UUID player,String name,String key,String value){config("config.read",actorKind,player,name,key,null,value);}
public void configChanged(String actorKind,UUID player,String name,String key,String before,String after){config("config.changed",actorKind,player,name,key,before,after);}
private void config(String type,String actorKind,UUID player,String name,String key,String before,String after){var action=UUID.randomUUID();var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(name!=null)data.put("actor_player_name",name);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application",key.startsWith("starting-")?"future_character_initialization":"future_mob_defeats");data.put("outcome","acknowledged");try{publish(new EventInput(id(action,type),action,clock.instant(),type,player==null?null:new EventInput.Context(player,name,null,null,null,null),Map.copyOf(data)));}catch(RuntimeException ignored){}}
public void configRead(String actorKind,UUID player,String name,String key,String value){configRead(UUID.randomUUID(),actorKind, player, name, key, value);}
public void configRead(UUID operation,String actorKind,UUID player,String name,String key,String value){config(operation,"config.read",actorKind, player, name, key,null,value);}
public void configChanged(String actorKind,UUID player,String name,String key,String before,String after){configChanged(UUID.randomUUID(),actorKind, player, name, key, before, after);}
public void configChanged(UUID operation,String actorKind,UUID player,String name,String key,String before,String after){config(operation,"config.changed",actorKind, player, name, key, before, after);}
private void config(UUID operation,String type,String actorKind,UUID player,String name,String key,String before,String after){var action=operation;var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(name!=null)data.put("actor_player_name",name);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application",key.startsWith("starting-")?"future_character_initialization":"future_mob_defeats");data.put("outcome","acknowledged");try{publish(new EventInput(id(action,type),action,clock.instant(),type,player==null?null:new EventInput.Context(player,name,null,null,null,null),Map.copyOf(data)));}catch(RuntimeException ignored){}}
private void emit(UUID action,String type,Map<String,Object> data){try{publish(new EventInput(id(action,type),action,clock.instant(),type,null,Map.copyOf(data)));}catch(RuntimeException ignored){}}
private static UUID stable(UUID character,String kind){return UUID.nameUUIDFromBytes(("fantasystick:coin:"+character+":"+kind).getBytes(StandardCharsets.UTF_8));}
private static UUID id(UUID action,String type){return UUID.nameUUIDFromBytes(("fantasystick:coin:"+action+":"+type).getBytes(StandardCharsets.UTF_8));}
@@ -200,18 +200,27 @@ public final class DownedEventBridge {
}
public void configRead(String actorKind, UUID player, String playerName, String key, String value) {
config("config.read", actorKind, player, playerName, key, null, value);
configRead(UUID.randomUUID(), actorKind, player, playerName, key, value);
}
public void configRead(UUID operation, String actorKind, UUID player, String playerName, String key, String value) {
config(operation, "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);
configChanged(UUID.randomUUID(), actorKind, player, playerName, key, before, after);
}
private void config(String type, String actorKind, UUID player, String playerName, String key,
public void configChanged(UUID operation, String actorKind, UUID player, String playerName, String key,
String before, String after) {
config(operation, "config.changed", actorKind, player, playerName, key, before, after);
}
private void config(UUID operation, String type, String actorKind, UUID player, String playerName, String key,
String before, String after) {
var now = clock.instant();
var action = UUID.randomUUID();
var action = operation;
var data = new LinkedHashMap<String, Object>();
data.put("actor_kind", Objects.requireNonNull(actorKind));
if (player != null) data.put("actor_player_id", player.toString());
@@ -108,9 +108,11 @@ public final class DungeonAuditEventBridge implements AutoCloseable {
else{data.put("actor_kind","unavailable");data.put("location_status","unavailable");}
// Match the unchanged writer envelope before journaling, retaining original-actor provenance separately.
if(actor==null||actor.context()==null){var original=data.get("actor_kind");if(!"console".equals(original)&&!"command_block".equals(original)){data.put("original_actor_kind",java.util.Objects.toString(original,"unavailable"));data.put("actor_kind","system");}}
var id=UUID.nameUUIDFromBytes(("fantasystick:dungeon-audit:"+operation+":"+type).getBytes(StandardCharsets.UTF_8));
var id=eventId(operation,type);
outbox.accepted(new EventInput(id,operation,clock.instant(),type,actor==null?null:actor.context(),data));
}
/** Stable original owner envelope identity; no log read or new publication. */
public static UUID eventId(UUID operation,String type){return UUID.nameUUIDFromBytes(("fantasystick:dungeon-audit:"+operation+":"+type).getBytes(StandardCharsets.UTF_8));}
public void replay(){outbox.replay();}
public CompletionStage<Void> drained(){return outbox.drained();}
@Override public void close(){outbox.close();}
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.DirectoryStream;
import java.util.Iterator;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@@ -18,7 +20,10 @@ import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -26,14 +31,80 @@ import java.util.function.Function;
/** Per-feature recoverable intent for acknowledged domain outcomes. Never replays gameplay. */
final class FeatureEventOutbox implements AutoCloseable {
private static final int MAX_BYTES = 16_384;
// Shared internal safety envelope: queued snapshots AND unsettled sink callbacks across all owners.
private static final int MAX_HANDOFFS = 1024;
private static final Semaphore HANDOFFS = new Semaphore(MAX_HANDOFFS);
// One small control record per live feature owner, never per rejected observation or pending file.
private static final Semaphore OWNER_SLOTS = new Semaphore(MAX_HANDOFFS);
private static final Set<FeatureEventOutbox> OWNERS = java.util.concurrent.ConcurrentHashMap.newKeySet();
private static final Object MAINTENANCE_LIFETIME = new Object();
private static java.util.concurrent.ScheduledExecutorService REPLAYS;
private static java.util.concurrent.ScheduledExecutorService DIAGNOSTICS;
private static void attach(FeatureEventOutbox owner) {
synchronized (MAINTENANCE_LIFETIME) {
OWNERS.add(owner);
if (REPLAYS == null) {
REPLAYS = maintenance("fantasy-feature-replay");
DIAGNOSTICS = maintenance("fantasy-feature-diagnostics");
REPLAYS.scheduleWithFixedDelay(() -> OWNERS.forEach(FeatureEventOutbox::continueReplay), 100, 100, TimeUnit.MILLISECONDS);
DIAGNOSTICS.scheduleWithFixedDelay(() -> OWNERS.forEach(FeatureEventOutbox::diagnose), 100, 100, TimeUnit.MILLISECONDS);
}
}
}
private static void detach(FeatureEventOutbox owner) {
synchronized (MAINTENANCE_LIFETIME) {
OWNERS.remove(owner);
if (OWNERS.isEmpty()) {
REPLAYS.shutdown(); DIAGNOSTICS.shutdown();
REPLAYS = null; DIAGNOSTICS = null;
}
}
}
private static java.util.concurrent.ScheduledExecutorService maintenance(String name) {
return java.util.concurrent.Executors.newSingleThreadScheduledExecutor(task -> {
var thread = new Thread(task, name); thread.setDaemon(true); return thread;
});
}
static final class HandoffRejection extends RejectedExecutionException {
private static final long serialVersionUID = 1L;
private final long rejected, deferred;
HandoffRejection(long rejected, long deferred) {
super("Feature audit handoff: " + rejected + " observations rejected before durable acceptance; "
+ deferred + " replay passes deferred with durable intents retained");
this.rejected = rejected; this.deferred = deferred;
}
long rejectedCount() { return rejected; }
long deferredCount() { return deferred; }
}
private final Set<String> types;
private final Path directory;
private final Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink;
private final Consumer<Throwable> failures;
private final ExecutorService worker = Executors.newSingleThreadExecutor(task ->
new Thread(task, "fantasy-feature-event-intents"));
private final ExecutorService worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(MAX_HANDOFFS), task -> new Thread(task, "fantasy-feature-event-intents"),
new ThreadPoolExecutor.AbortPolicy()) {
@Override protected void terminated() { closeReplayCursor(); }
};
private final CompletableFuture<Void> drained = new CompletableFuture<>();
private final Set<UUID> inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet();
// 0 detached, 1 attached, 2 retiring, 3 registering: no caller waits for maintenance or I/O.
private final java.util.concurrent.atomic.AtomicInteger registration = new java.util.concurrent.atomic.AtomicInteger();
private final java.util.concurrent.atomic.AtomicBoolean closed = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicBoolean replayQueued = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicBoolean diagnosing = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicBoolean closingDiagnosis = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicLong rejected = new java.util.concurrent.atomic.AtomicLong();
private final java.util.concurrent.atomic.AtomicLong deferred = new java.util.concurrent.atomic.AtomicLong();
private final Object diagnosticFence = new Object();
private volatile long lastDiagnostic;
private volatile boolean replayRequested;
// The directory cursor is confined to the intent worker; it retains no materialized backlog.
private DirectoryStream<Path> replayFiles;
private Iterator<Path> replayPaths;
FeatureEventOutbox(Path data, String folder, Set<String> types,
Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
@@ -43,27 +114,111 @@ final class FeatureEventOutbox implements AutoCloseable {
this.types = Set.copyOf(types);
this.sink = sink;
this.failures = failures;
if (!register()) throw new RejectedExecutionException("Feature audit owner capacity exhausted");
}
private boolean register() {
if (!registration.compareAndSet(0, 3)) return true;
if (!OWNER_SLOTS.tryAcquire()) { registration.set(0); return false; }
attach(this); registration.set(1); return true;
}
private void retire() {
if (!worker.isTerminated() || rejected.get() != 0 || deferred.get() != 0 || diagnosing.get()) return;
if (!registration.compareAndSet(1, 2)) return;
detach(this); OWNER_SLOTS.release(); registration.set(0);
// A producer seeing state 2 cannot reattach until removal finishes; its counts remain owned here.
if (rejected.get() != 0 || deferred.get() != 0) register();
}
private void rejectObservation() { rejected.incrementAndGet(); register(); }
private void diagnose() {
if (!diagnosing.compareAndSet(false, true)) return;
try {
long now = System.nanoTime();
if (!closingDiagnosis.getAndSet(false) && lastDiagnostic != 0
&& now - lastDiagnostic < TimeUnit.SECONDS.toNanos(1)) return;
long lost = rejected.getAndSet(0), delayed = deferred.getAndSet(0);
if (lost != 0 || delayed != 0) {
lastDiagnostic = now;
report(new HandoffRejection(lost, delayed));
}
} finally {
diagnosing.set(false);
synchronized (diagnosticFence) { diagnosticFence.notifyAll(); }
retire();
}
}
void accepted(EventInput event) {
if (!admit()) return;
try { worker.execute(() -> {
try { publish(write(event)); } catch (IOException | RuntimeException failure) { report(failure); }
}); } catch (RuntimeException failure) { report(failure); }
EventInput saved;
try { saved = write(event); }
catch (IOException | RuntimeException failure) { HANDOFFS.release(); report(failure); return; }
publish(saved); // The admission remains owned until delivery settles, not merely until dequeue.
}); } catch (RejectedExecutionException failure) { HANDOFFS.release(); rejectObservation(); }
}
private boolean admit() {
if (closed.get() || worker.isShutdown() || !HANDOFFS.tryAcquire()) {
rejectObservation();
return false;
}
return true;
}
void replay() {
if (worker.isShutdown()) return;
try { worker.execute(() -> {
try {
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) return;
if (closed.get()) return;
replayRequested = true;
continueReplay();
}
private void continueReplay() {
if (!replayRequested || closed.get() || !replayQueued.compareAndSet(false, true)) return;
// The command and its next handoff both need a slot. Never wait or do caller-thread I/O.
if (HANDOFFS.availablePermits() < 2 || !HANDOFFS.tryAcquire()) {
replayQueued.set(false);
if (deferred.compareAndSet(0, 1)) register();
return;
}
try { worker.execute(this::replayBatch); }
catch (RejectedExecutionException failure) {
HANDOFFS.release(); replayQueued.set(false); deferred.compareAndSet(0, 1);
}
}
private void replayBatch() {
try {
if (replayFiles == null) {
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { replayRequested = false; return; }
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe character event directory");
try (var files = Files.list(directory)) {
for (var path : files.filter(value -> value.getFileName().toString().endsWith(".pending")).sorted().toList()) {
try { publish(read(path)); } catch (IOException | RuntimeException failure) { report(failure); }
}
replayFiles = Files.newDirectoryStream(directory, "*.pending");
replayPaths = replayFiles.iterator();
}
while (replayPaths.hasNext()) {
if (!HANDOFFS.tryAcquire()) {
deferred.compareAndSet(0, 1);
return; // Resume this same bounded cursor after any owner's acknowledgment releases capacity.
}
} catch (IOException | RuntimeException failure) { report(failure); }
}); } catch (RuntimeException failure) { report(failure); }
EventInput saved;
try { saved = read(replayPaths.next()); }
catch (IOException | RuntimeException failure) { HANDOFFS.release(); report(failure); continue; }
publish(saved);
}
replayRequested = false;
} catch (IOException | RuntimeException failure) { replayRequested = false; report(failure); }
finally {
if (!replayRequested || closed.get()) closeReplayCursor();
replayQueued.set(false); HANDOFFS.release();
}
}
private void closeReplayCursor() {
if (replayFiles == null) return;
try { replayFiles.close(); } catch (IOException failure) { report(failure); }
finally { replayFiles = null; replayPaths = null; }
}
private Path path(EventInput event) { return directory.resolve(event.id() + ".pending"); }
@@ -240,16 +395,17 @@ final class FeatureEventOutbox implements AutoCloseable {
}
private void publish(EventInput event) {
if (!inFlight.add(event.id())) return;
if (!inFlight.add(event.id())) { HANDOFFS.release(); return; }
try { sink.apply(event).whenComplete((delivery, failure) -> {
try {
if (failure != null) { report(failure); return; }
if (delivery == LocalEventLog.Delivery.REJECTED) return;
try { if (Files.deleteIfExists(path(event))) forceDirectory(); }
catch (IOException error) { report(error); }
} finally { inFlight.remove(event.id()); }
} finally { inFlight.remove(event.id()); HANDOFFS.release(); }
}); } catch (RuntimeException failure) {
inFlight.remove(event.id());
HANDOFFS.release();
report(failure);
}
}
@@ -263,13 +419,23 @@ final class FeatureEventOutbox implements AutoCloseable {
}
@Override public void close() {
if (!closed.compareAndSet(false, true)) return;
closingDiagnosis.set(true);
worker.shutdown();
CompletableFuture.runAsync(() -> {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
try {
if (!worker.awaitTermination(5, TimeUnit.SECONDS)) report(new IOException("Character event intents did not drain"));
synchronized (diagnosticFence) {
while (rejected.get() != 0 || deferred.get() != 0 || diagnosing.get()) {
long remaining = deadline - System.nanoTime();
if (remaining <= 0) break; // Bounded shutdown attempt; maintenance retains the aggregate diagnosis.
TimeUnit.NANOSECONDS.timedWait(diagnosticFence, remaining);
}
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt(); report(interrupted);
} finally { drained.complete(null); }
} finally { retire(); drained.complete(null); }
});
}
@@ -95,10 +95,14 @@ public final class FishingEventBridge implements AutoCloseable {
}
public void configRead(Actor actor, String key, String effective, String defaultValue) {
configRead(UUID.randomUUID(), actor, key, effective, defaultValue);
}
public void configRead(UUID operation, Actor actor, String key, String effective, String defaultValue) {
if (actor == null) return;
var data = config(actor, key, defaultValue);
data.put("effective", effective); data.put("outcome", "acknowledged_read");
transientEvent("config.read", UUID.randomUUID(), actor, data);
transientEvent("config.read", operation, actor, data);
}
public void configChanged(Actor actor, UUID operation, String key, String before,
@@ -45,7 +45,11 @@ public final class HardMobXpEventBridge implements AutoCloseable {
}
public void read(Actor actor, String value) {
record("config.read", actor, UUID.randomUUID(), null, value);
read(UUID.randomUUID(), actor, value);
}
public void read(UUID operation, Actor actor, String value) {
record("config.read", actor, operation, null, value);
}
public void changed(Actor actor, UUID operation, String before, String value) {
@@ -50,11 +50,14 @@ public final class PartyCapacityEventBridge implements AutoCloseable {
}
public void read(Actor actor, String effective) {
read(UUID.randomUUID(), actor, effective);
}
public void read(UUID operation, Actor actor, String effective) {
if (actor == null) return;
var values = common(actor);
values.put("effective", effective);
values.put("outcome", "acknowledged_read");
var operation = UUID.randomUUID();
try { sink.apply(new EventInput(id(operation, "config.read"), operation, clock.instant(),
"config.read", actor.context(), values)); }
catch (RuntimeException ignored) { /* Observation cannot change party capacity. */ }
@@ -33,14 +33,16 @@ public final class PartyEventBridge {
public void registrarPlaced(String actorKind,UUID actorPlayer,String actorName,PartyRegistrar registrar,UUID entity,boolean loaded){registrar("party_registrar.placed",actorKind,actorPlayer,actorName,registrar,entity,loaded,"registered_and_reconciled");}
public void registrarRemoved(String actorKind,UUID actorPlayer,String actorName,PartyRegistrar registrar,UUID entity,boolean loaded){registrar("party_registrar.removed",actorKind,actorPlayer,actorName,registrar,entity,loaded,"registration_removed");}
public void finalDefeat(UUID character,CharacterParty before,CharacterPartyDirectory.Defeat outcome){if(before==null||outcome==CharacterPartyDirectory.Defeat.UNCHANGED)return;var action=stable(before.id(),character,before.revision(),"final-death");var data=partyData(before,null);data.put("reason","final_death");data.put("subject_character_id",character.toString());data.put("popup_delivery",outcome==CharacterPartyDirectory.Defeat.PARTY_DISBANDED?"active_former_member_delivery_queued":"not_applicable");data.put("outcome","acknowledged");data.put("operation_id",action.toString());emit(id(action,outcome==CharacterPartyDirectory.Defeat.PARTY_DISBANDED?"party.disbanded":"party.left"),action,clock.instant(),outcome==CharacterPartyDirectory.Defeat.PARTY_DISBANDED?"party.disbanded":"party.left",null,data);}
public void configRead(String actorKind,UUID player,String name,String key,String value){config("config.read",actorKind,player,name,key,null,value);}
public void configChanged(String actorKind,UUID player,String name,String key,String before,String after){config("config.changed",actorKind,player,name,key,before,after);}
public void configRead(String actorKind,UUID player,String name,String key,String value){configRead(UUID.randomUUID(),actorKind, player, name, key, value);}
public void configRead(UUID operation,String actorKind,UUID player,String name,String key,String value){config(operation,"config.read",actorKind, player, name, key,null,value);}
public void configChanged(String actorKind,UUID player,String name,String key,String before,String after){configChanged(UUID.randomUUID(),actorKind, player, name, key, before, after);}
public void configChanged(UUID operation,String actorKind,UUID player,String name,String key,String before,String after){config(operation,"config.changed",actorKind, player, name, key, before, after);}
private void emitAction(String type,Action action,String outcome,String reason,CharacterParty after,CharacterPartyDirectory.Offer invitation){var data=partyData(action.before(),after);data.put("action_kind","party_"+action.kind());data.put("operation_id",action.id().toString());data.put("registrar_id",action.registrar().id().toString());data.put("registrar_location",registrarLocation(action.registrar()));data.put("actor_character_id",action.context().characterId().toString());data.put("actor_player_id",action.context().playerId().toString());data.put("actor_session_id",action.context().sessionId().toString());if(action.target()!=null)data.put("target_character_id",action.target().toString());if(action.targetContext()!=null){data.put("target_player_id",action.targetContext().playerId().toString());data.put("target_session_id",action.targetContext().sessionId().toString());if(action.targetContext().playerName()!=null)data.put("target_player_name",action.targetContext().playerName());if(action.targetContext().location()!=null)data.put("target_location",locationData(action.targetContext().location()));}if(action.invitation()!=null)data.put("invitation_id",action.invitation().toString());else if(invitation!=null)data.put("invitation_id",invitation.id().toString());if(action.charge().signum()>0){data.put("charged_coins",action.charge().toString());data.put("charge_receipt",action.id().toString());}data.put("reason",action.reason());data.put("popup_delivery",type.equals("party.disbanded")?"active_former_member_delivery_queued":"not_applicable");data.put("outcome",outcome);if(reason!=null)data.put(type.startsWith("party.")?"mutation_boundary":"reason",reason);emit(id(action.id(),type),action.id(),clock.instant(),type,action.context(),data);}
private static String type(String kind,CharacterParty before,CharacterParty after){return switch(kind){case "create"->"party.created";case "invite"->"party.invitation_created";case "cancel"->"party.invitation_cancelled";case "decline"->"party.invitation_declined";case "accept"->"party.joined";case "kick"->"party.member_kicked";case "transfer"->"party.leadership_transferred";case "disband","leader_leave"->"party.disbanded";case "leave"->before!=null&&before.leader().equals(before.members().stream().filter(id->after==null||!after.members().contains(id)).findFirst().orElse(null))?"party.disbanded":"party.left";default->"party.mutated";};}
private static LinkedHashMap<String,Object> partyData(CharacterParty before,CharacterParty after){var data=new LinkedHashMap<String,Object>();var party=after==null?before:after;if(party!=null){data.put("party_id",party.id().toString());data.put("party_display_name",party.displayName());data.put("party_canonical_name",party.canonicalName());}if(before!=null){data.put("before_revision",before.revision().toString());data.put("before_leader_character_id",before.leader().toString());data.put("before_member_character_ids",before.members().stream().map(UUID::toString).sorted().toList());}if(after!=null){data.put("after_revision",after.revision().toString());data.put("after_leader_character_id",after.leader().toString());data.put("after_member_character_ids",after.members().stream().map(UUID::toString).sorted().toList());}return data;}
private void registrar(String type,String actorKind,UUID actorPlayer,String actorName,PartyRegistrar registrar,UUID entity,boolean loaded,String outcome){var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(actorPlayer!=null)data.put("actor_player_id",actorPlayer.toString());if(actorName!=null)data.put("actor_player_name",actorName);data.put("registrar_id",registrar.id().toString());data.put("registrar_name",registrar.name());data.put("registrar_revision","0");data.put("operation_id",registrar.id().toString());data.put("registered_location",registrarLocation(registrar));if(entity!=null)data.put("entity_id",entity.toString());data.put("entity_status",loaded?"loaded":"unloaded");data.put("outcome",outcome);emit(id(registrar.id(),type),registrar.id(),clock.instant(),type,actorPlayer==null?null:new EventInput.Context(actorPlayer,actorName,null,null,null,null),data);}
private void config(String type,String actorKind,UUID player,String name,String key,String before,String after){var action=UUID.randomUUID();var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(name!=null)data.put("actor_player_name",name);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application","future_party_transactions");data.put("outcome","acknowledged");emit(id(action,type),action,clock.instant(),type,player==null?null:new EventInput.Context(player,name,null,null,null,null),data);}
private void config(UUID operation,String type,String actorKind,UUID player,String name,String key,String before,String after){var action=operation;var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(name!=null)data.put("actor_player_name",name);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application","future_party_transactions");data.put("outcome","acknowledged");emit(id(action,type),action,clock.instant(),type,player==null?null:new EventInput.Context(player,name,null,null,null,null),data);}
private static Map<String,Object> locationData(EventInput.Location value){return Map.of("world_id",value.worldId().toString(),"world_name",value.worldName(),"x",value.x(),"y",value.y(),"z",value.z(),"captured_at",value.capturedAt().toString(),"quality",value.quality());}
private static Map<String,Object> registrarLocation(PartyRegistrar value){return Map.of("world_id",value.world().toString(),"x",Double.toString(value.x()),"y",Double.toString(value.y()),"z",Double.toString(value.z()),"yaw",Float.toString(value.yaw()),"pitch",Float.toString(value.pitch()),"quality","registered_exact");}
public EventInput.Context context(Player player,games.dmg.fantasystick.session.EquipmentSessions.Active active,String name){return new EventInput.Context(player.getUniqueId(),player.getName(),active.character(),name,active.session(),location(player.getLocation()));}
@@ -27,15 +27,19 @@ public final class PassiveEventBridge {
public void refused(org.bukkit.entity.Player player,EquipmentSessions.Active active,CharacterRecord before,PassiveDefinition definition,boolean learn,String reason){var action=captureAction(player,active,before,definition,learn);emit("action.observed",action,"observed",null,null);emit("action.resolved",action,"refused",reason,null);}
public void failed(Action action,String reason){emit("action.resolved",action,"failed",reason,null);}
public void resolved(Action action,PassiveEngine.Mutation mutation){if(mutation!=null&&mutation.status()==games.dmg.fantasystick.persistence.CharacterStorage.PassiveMutationStatus.APPLIED&&mutation.record()!=null){emit("action.resolved",action,"accepted","acknowledged",mutation.record());emit(action.learn()?"passive.learned":"passive.unlearned",action,"accepted","acknowledged",mutation.record());}else emit("action.resolved",action,"refused",mutation==null?"unavailable":mutation.status().name().toLowerCase(java.util.Locale.ROOT),mutation==null?null:mutation.record());}
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);}
public void configRead(String actorKind,UUID player,String playerName,String key,String value){configRead(UUID.randomUUID(),actorKind,player,playerName,key,value);}
public void configRead(UUID operation,String actorKind,UUID player,String playerName,String key,String value){config(operation,"config.read",actorKind,player,playerName,key,null,value);}
public void configChanged(String actorKind,UUID player,String playerName,String key,String before,String after){configChanged(UUID.randomUUID(),actorKind,player,playerName,key,before,after);}
public void configChanged(UUID operation,String actorKind,UUID player,String playerName,String key,String before,String after){config(operation,"config.changed",actorKind,player,playerName,key,before,after);}
private void emit(String type,Action action,String outcome,String reason,CharacterRecord after){var before=action.before();var data=new LinkedHashMap<String,Object>();data.put("action_kind",action.learn()?"passive_learn":"passive_unlearn");data.put("passive_id",action.passive());data.put("expected_revision",before.revision().toString());data.put("before_revision",before.revision().toString());data.put("points_before",before.unspentPoints().toString());data.put("point_cost",action.definition().pointCost().toString());var requirements=new LinkedHashMap<String,Object>();action.definition().requirements().entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry->requirements.put(entry.getKey().name(),entry.getValue().toString()));data.put("stat_prerequisites",requirements);var statValues=new LinkedHashMap<String,Object>();action.definition().requirements().keySet().stream().sorted().forEach(stat->{var value=before.stats().get(stat);if(value!=null)statValues.put(stat.name(),value.toString());});data.put("stat_values_before",statValues);data.put("passive_slots_before",before.passives());data.put("passive_prerequisites",action.definition().prerequisites().stream().sorted().toList());data.put("outcome",outcome);data.putAll(action.actorMetadata());if(after!=null){data.put("after_revision",after.revision().toString());data.put("points_after",after.unspentPoints().toString());data.put("passive_slots_after",after.passives());int slot=(action.learn()?after.passives():before.passives()).indexOf(action.passive());data.put("passive_slot",slot);data.put("slot_index_base",0);data.put("native_publication","acknowledged");data.put("owned_cleanup",action.learn()?"passive_state_acknowledged":"passive_state_acknowledged");}if(reason!=null)data.put(type.startsWith("passive.")?"native_boundary":"reason",reason);try{sink.accept(new EventInput(id(action.actionId(),type),action.actionId(),clock.instant(),type,action.context(),Map.copyOf(data)));}catch(RuntimeException ignored){}
}
public void configRead(String actorKind,UUID player,String playerName,String key,String value,String application){config("config.read",actorKind,player,playerName,key,null,value,application);}
public void configChanged(String actorKind,UUID player,String playerName,String key,String before,String after,String application){config("config.changed",actorKind,player,playerName,key,before,after,application);}
private void config(String type,String actorKind,UUID player,String playerName,String key,String before,String after){config(type,actorKind,player,playerName,key,before,after,"future_recovery_pulses");}
private void config(String type,String actorKind,UUID player,String playerName,String key,String before,String after,String application){var action=UUID.randomUUID();var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(playerName!=null)data.put("actor_player_name",playerName);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application",application);data.put("outcome","acknowledged");var context=player==null?null:new EventInput.Context(player,playerName,null,null,null,null);try{sink.accept(new EventInput(id(action,type),action,clock.instant(),type,context,Map.copyOf(data)));}catch(RuntimeException ignored){}
public void configRead(String actorKind,UUID player,String playerName,String key,String value,String application){configRead(UUID.randomUUID(),actorKind,player,playerName,key,value,application);}
public void configRead(UUID operation,String actorKind,UUID player,String playerName,String key,String value,String application){config(operation,"config.read",actorKind,player,playerName,key,null,value,application);}
public void configChanged(String actorKind,UUID player,String playerName,String key,String before,String after,String application){configChanged(UUID.randomUUID(),actorKind,player,playerName,key,before,after,application);}
public void configChanged(UUID operation,String actorKind,UUID player,String playerName,String key,String before,String after,String application){config(operation,"config.changed",actorKind,player,playerName,key,before,after,application);}
private void config(UUID operation,String type,String actorKind,UUID player,String playerName,String key,String before,String after){config(operation,type,actorKind,player,playerName,key,before,after,"future_recovery_pulses");}
private void config(UUID operation,String type,String actorKind,UUID player,String playerName,String key,String before,String after,String application){var action=operation;var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);if(player!=null)data.put("actor_player_id",player.toString());if(playerName!=null)data.put("actor_player_name",playerName);data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);data.put("application",application);data.put("outcome","acknowledged");var context=player==null?null:new EventInput.Context(player,playerName,null,null,null,null);try{sink.accept(new EventInput(id(action,type),action,clock.instant(),type,context,Map.copyOf(data)));}catch(RuntimeException ignored){}
}
private Action captureAction(org.bukkit.entity.Player player,EquipmentSessions.Active active,CharacterRecord before,PassiveDefinition definition,boolean learn){
if(!games.dmg.fantasystick.passive.StickKnockback.ID.equals(definition.id()))return new Action(UUID.randomUUID(),context(player,active,before.name()),definition.id(),learn,definition,before);
@@ -74,19 +74,17 @@ public final class RareEventBridge implements AutoCloseable {
emit(stable(operation,product==RareProduct.PHOENIX_DOWN?"phoenix-purchased":"rare-purchased"),operation,
clock.instant(),"rare_item.purchased",context,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){
public void configRead(String actorKind,UUID player,String playerName,String key,String value){configRead(UUID.randomUUID(),actorKind, player, playerName, key, value);}
public void configRead(UUID operation,String actorKind,UUID player,String playerName,String key,String value){config(operation,"config.read",actorKind, player, playerName, key,null,value);}
public void configChanged(String actorKind,UUID player,String playerName,String key,String before,String after){configChanged(UUID.randomUUID(),actorKind, player, playerName, key, before, after);}
public void configChanged(UUID operation,String actorKind,UUID player,String playerName,String key,String before,String after){config(operation,"config.changed",actorKind, player, playerName, key, before, after);}
private void config(UUID operation,String type,String actorKind,UUID player,String playerName,String key,String before,String after){
var data=new LinkedHashMap<String,Object>();data.put("actor_kind",actorKind);
if(player!=null)data.put("actor_player_id",player.toString());
if(playerName!=null)data.put("actor_player_name",playerName);
data.put("key",key);if(before!=null)data.put("before",before);data.put("after",after);
data.put("application",key.endsWith("-healing-percent")?"future_potion_uses":"next_rare_restock");
data.put("outcome","acknowledged");var operation=UUID.randomUUID();
data.put("outcome","acknowledged");
var context=player==null?null:new EventInput.Context(player,playerName,null,null,null,null);
emit(stable(operation,type),operation,clock.instant(),type,context,data);
}
@@ -65,11 +65,14 @@ public final class RecoveryEventBridge implements AutoCloseable {
}
public void configRead(Actor actor, String key, String effective) {
configRead(UUID.randomUUID(), actor, key, effective);
}
public void configRead(UUID operation, Actor actor, String key, String effective) {
if (actor == null) return;
var values = config(actor, key);
values.put("effective", effective);
values.put("outcome", "acknowledged_read");
var operation = UUID.randomUUID();
try { sink.accept(new EventInput(id(operation, "config.read"), operation, clock.instant(),
"config.read", actor.context(), values)); }
catch (RuntimeException ignored) { /* Audit reads cannot change recovery. */ }
@@ -50,12 +50,15 @@ public final class RoleplayAvailabilityEventBridge implements AutoCloseable {
}
public void read(Actor actor, boolean disabled) {
read(UUID.randomUUID(), actor, disabled);
}
public void read(UUID operation, Actor actor, boolean disabled) {
if (actor == null) return;
var values = common(actor);
values.put("effective", disabled);
values.put("available", !disabled);
values.put("outcome", "acknowledged_read");
var operation = UUID.randomUUID();
try { sink.apply(new EventInput(id(operation, "config.read"), operation, clock.instant(),
"config.read", actor.context(), values)); }
catch (RuntimeException ignored) { /* An observation cannot change availability. */ }
@@ -57,11 +57,15 @@ public final class SheetResourcePackEventBridge implements AutoCloseable {
}
public void read(Actor actor, String key, String value) {
read(UUID.randomUUID(), actor, key, value);
}
public void read(UUID operation, Actor actor, String key, String value) {
if (actor == null) return;
var values = config(actor, key);
values.put("effective", safeValue(key, value));
values.put("outcome", "acknowledged_read");
var action = UUID.randomUUID();
var action = operation;
try { sink.apply(new EventInput(id(action, "config.read"), action, clock.instant(),
"config.read", actor.context(), values)); }
catch (RuntimeException ignored) { /* A read cannot change a delivery. */ }
@@ -50,11 +50,15 @@ public final class SwitchConfigEventBridge implements AutoCloseable {
}
public void read(Actor actor, String effective) {
read(UUID.randomUUID(), actor, effective);
}
public void read(UUID operation, Actor actor, String effective) {
if (actor == null) return;
var data = common(actor);
data.put("effective", effective);
data.put("outcome", "acknowledged_read");
var action = UUID.randomUUID();
var action = operation;
try { sink.apply(new EventInput(id(action, "config.read"), action, clock.instant(),
"config.read", actor.context(), data)); }
catch (RuntimeException ignored) { /* Observation cannot change the policy. */ }
@@ -36,7 +36,7 @@ public final class AdminReviveSettings implements AutoCloseable {
private static Duration validate(Duration value){long seconds;try{seconds=value.toSeconds();}catch(ArithmeticException invalid){throw new IllegalArgumentException("Invalid admin revival timeout",invalid);}if(value.isZero()||value.isNegative()||value.getNano()!=0||seconds>MAX_SECONDS)throw new IllegalArgumentException(KEY+" must be positive whole seconds through 365 days");return value;}
public Duration timeout(){return effective;}public String value(){return Long.toString(effective.toSeconds());}
public CompletionStage<Update> set(String raw){Duration accepted=parse(raw);synchronized(this){if(closed)return CompletableFuture.failedStage(new IOException("Configuration store is closed"));pending++;}try{return CompletableFuture.supplyAsync(()->{try{save(accepted);persisted=accepted;return new Update(Long.toString(accepted.toSeconds()),accepted,++persistedSequence);}catch(IOException|RuntimeException failure){throw new java.util.concurrent.CompletionException(new IOException("Admin revival configuration save refused or failed; effective setting unchanged"));}finally{finished();}},worker).minimalCompletionStage();}catch(RejectedExecutionException rejected){finished();return CompletableFuture.failedStage(new IOException("Configuration store is closed"));}}
public synchronized void publish(Update update){if(update.sequence()<=publishedSequence)return;effective=validate(update.timeout());publishedSequence=update.sequence();}
public synchronized boolean publish(Update update){if(update.sequence()<=publishedSequence)return false;effective=validate(update.timeout());publishedSequence=update.sequence();return true;}
private void save(Duration value)throws IOException{Files.createDirectories(directory);if(!Files.isDirectory(directory,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe directory");var file=directory.resolve("config.yml");var lockFile=directory.resolve(".config.lock");if(Files.exists(lockFile,LinkOption.NOFOLLOW_LINKS)&&!Files.isRegularFile(lockFile,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe lock");try(var channel=FileChannel.open(lockFile,StandardOpenOption.CREATE,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS);var lock=channel.tryLock()){if(lock==null)throw new IOException("Configuration busy");var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(20);options.setCodePointLimit(MAX_BYTES);var yaml=new Yaml(new SafeConstructor(options));Map<String,Object> values=new LinkedHashMap<>();if(Files.exists(file,LinkOption.NOFOLLOW_LINKS)){if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe configuration");byte[] bytes;try(var input=Files.newInputStream(file,LinkOption.NOFOLLOW_LINKS)){bytes=input.readNBytes(MAX_BYTES+1);}if(bytes.length>MAX_BYTES)throw new IOException("Configuration too large");Object loaded=yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());if(loaded!=null){if(!(loaded instanceof Map<?,?> map))throw new IOException("Invalid configuration root");for(var entry:map.entrySet()){if(!(entry.getKey() instanceof String key))throw new IOException("Invalid configuration key");values.put(key,entry.getValue());}}}values.put(KEY,Long.toString(value.toSeconds()));byte[] bytes=yaml.dump(values).getBytes(StandardCharsets.UTF_8);if(bytes.length>MAX_BYTES)throw new IOException("Configuration too large");Path temporary=Files.createTempFile(directory,".config-",".tmp");try{try(var output=FileChannel.open(temporary,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())output.write(buffer);output.force(true);}replacement.move(temporary,file);}finally{Files.deleteIfExists(temporary);}}catch(OverlappingFileLockException busy){throw new IOException("Configuration busy");}}
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);}
}
@@ -34,9 +34,11 @@ public final class ChainLightningSettings implements AutoCloseable {
public static final String JUMP_RANGE = "chain-lightning-jump-range-blocks";
public static final String ADDITIONAL = "chain-lightning-additional-targets";
public static final String MULTIPLIER = "chain-lightning-jump-multiplier";
private static final List<String> KEYS = List.of(BASE, COOLDOWN, INITIAL_RANGE, JUMP_RANGE, ADDITIONAL, MULTIPLIER);
public static final String INT_STEP = "chain-lightning-target-int-step";
public static final String MAX_TARGETS = "chain-lightning-max-targets";
private static final List<String> KEYS = List.of(BASE, COOLDOWN, INITIAL_RANGE, JUMP_RANGE, ADDITIONAL, MULTIPLIER, INT_STEP, MAX_TARGETS);
private static final Map<String, String> DEFAULTS = Map.of(
BASE, "8", COOLDOWN, "18", INITIAL_RANGE, "16", JUMP_RANGE, "6", ADDITIONAL, "3", MULTIPLIER, "0.75");
BASE, "8", COOLDOWN, "18", INITIAL_RANGE, "16", JUMP_RANGE, "6", ADDITIONAL, "4", MULTIPLIER, "0.75", INT_STEP, "5", MAX_TARGETS, "12");
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
public record Update(String key, String value, ChainLightning.Settings settings, Map<String, String> values, long sequence) {
@@ -112,7 +114,8 @@ public final class ChainLightningSettings implements AutoCloseable {
public static ChainLightning.Settings parse(Map<String, String> values) {
try { return new ChainLightning.Settings(new BigDecimal(values.get(BASE)).toBigIntegerExact(),
seconds(values.get(COOLDOWN)), finite(values.get(INITIAL_RANGE)), finite(values.get(JUMP_RANGE)),
new BigDecimal(values.get(ADDITIONAL)).intValueExact(), new BigDecimal(values.get(MULTIPLIER))); }
new BigDecimal(values.get(ADDITIONAL)).intValueExact(), new BigDecimal(values.get(MULTIPLIER)),
new BigDecimal(values.get(INT_STEP)).toBigIntegerExact(), new BigDecimal(values.get(MAX_TARGETS)).intValueExact()); }
catch (ArithmeticException | NumberFormatException | NullPointerException invalid) {
throw new IllegalArgumentException("Chain Lightning settings must use supported numeric values", invalid);
}
@@ -35,7 +35,7 @@ public final class FrostShardSettings implements AutoCloseable {
public static final String AMPLIFIER = "frost-shard-slowness-amplifier";
public static final String SLOWNESS = "frost-shard-slowness-duration-seconds";
private static final List<String> KEYS = List.of(BASE_DAMAGE, COOLDOWN, LIFETIME, SPEED, RANGE, AMPLIFIER, SLOWNESS);
private static final Map<String, String> DEFAULTS = Map.of(BASE_DAMAGE, "4", COOLDOWN, "5", RANGE, "32",
private static final Map<String, String> DEFAULTS = Map.of(BASE_DAMAGE, "4", COOLDOWN, "5", RANGE, "48",
LIFETIME, "5", SPEED, "3", AMPLIFIER, "0", SLOWNESS, "2");
@FunctionalInterface interface Replacement { void move(Path from, Path to) throws IOException; }
@@ -36,7 +36,7 @@ public final class SwitchDelaySettings implements AutoCloseable {
private static Duration validate(Duration value){if(value.isNegative()||value.getNano()!=0)throw new IllegalArgumentException(KEY+" must be nonnegative whole seconds");try{var deadline=java.time.Instant.now().plus(value);if(deadline.atOffset(java.time.ZoneOffset.UTC).getYear()>9999)throw new IllegalArgumentException(KEY+" exceeds the persisted timestamp range");return value;}catch(java.time.DateTimeException|ArithmeticException invalid){throw new IllegalArgumentException(KEY+" exceeds the persisted timestamp range",invalid);}}
public Duration delay(){return effective;}public String value(){return Long.toString(effective.toSeconds());}
public CompletionStage<Update> set(String raw){Duration accepted=parse(raw);synchronized(this){if(closed)return CompletableFuture.failedStage(new IOException("Configuration store is closed"));pending++;}try{return CompletableFuture.supplyAsync(()->{try{save(accepted);return new Update(Long.toString(accepted.toSeconds()),accepted,++persistedSequence);}catch(IOException|RuntimeException failure){throw new java.util.concurrent.CompletionException(new IOException("Character switch configuration save refused or failed; effective setting unchanged"));}finally{finished();}},worker).minimalCompletionStage();}catch(RejectedExecutionException rejected){finished();return CompletableFuture.failedStage(new IOException("Configuration store is closed"));}}
public synchronized void publish(Update update){if(update.sequence()<=publishedSequence)return;effective=validate(update.delay());publishedSequence=update.sequence();}
public synchronized boolean publish(Update update){if(update.sequence()<=publishedSequence)return false;effective=validate(update.delay());publishedSequence=update.sequence();return true;}
private void save(Duration value)throws IOException{Files.createDirectories(directory);if(!Files.isDirectory(directory,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe directory");var file=directory.resolve("config.yml");var lockFile=directory.resolve(".config.lock");if(Files.exists(lockFile,LinkOption.NOFOLLOW_LINKS)&&!Files.isRegularFile(lockFile,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe lock");try(var channel=FileChannel.open(lockFile,StandardOpenOption.CREATE,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS);var lock=channel.tryLock()){if(lock==null)throw new IOException("Configuration busy");var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(20);options.setCodePointLimit(MAX_BYTES);var yaml=new Yaml(new SafeConstructor(options));Map<String,Object> values=new LinkedHashMap<>();if(Files.exists(file,LinkOption.NOFOLLOW_LINKS)){if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS))throw new IOException("Unsafe configuration");byte[] bytes;try(var input=Files.newInputStream(file,LinkOption.NOFOLLOW_LINKS)){bytes=input.readNBytes(MAX_BYTES+1);}if(bytes.length>MAX_BYTES)throw new IOException("Configuration too large");Object loaded=yaml.load(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString());if(loaded!=null){if(!(loaded instanceof Map<?,?> map))throw new IOException("Invalid configuration root");for(var entry:map.entrySet()){if(!(entry.getKey() instanceof String key))throw new IOException("Invalid configuration key");values.put(key,entry.getValue());}}}values.put(KEY,Long.toString(value.toSeconds()));byte[] bytes=yaml.dump(values).getBytes(StandardCharsets.UTF_8);if(bytes.length>MAX_BYTES)throw new IOException("Configuration too large");Path temporary=Files.createTempFile(directory,".config-",".tmp");try{try(var output=FileChannel.open(temporary,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())output.write(buffer);output.force(true);}replacement.move(temporary,file);}finally{Files.deleteIfExists(temporary);}}catch(OverlappingFileLockException busy){throw new IOException("Configuration busy");}}
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);}
}
@@ -1,5 +1,6 @@
package games.dmg.fantasystick.session;
import games.dmg.fantasystick.events.AdminActionEventBridge;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.persistence.CharacterStorage;
@@ -24,6 +25,18 @@ public final class AdminCharacterIssuer implements AutoCloseable {
private final ConcurrentHashMap<UUID, Attempt> pending = new ConcurrentHashMap<>();
private volatile boolean closed;
private games.dmg.fantasystick.events.CharacterIdentityEventBridge identityEvents;
private AdminActionEventBridge adminAudit;
public void attachAdminAudit(AdminActionEventBridge audit) {
if (closed || adminAudit != null) throw new IllegalStateException("Character issue audit already attached");
adminAudit = Objects.requireNonNull(audit);
}
private void audit(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome outcome,
String reason, java.util.Map<String, Object> facts) {
var bridge = adminAudit;
if (bridge != null) bridge.result(action, outcome, reason, facts);
}
public void attachIdentityEvents(games.dmg.fantasystick.events.CharacterIdentityEventBridge events) {
identityEvents = Objects.requireNonNull(events);
@@ -40,20 +53,33 @@ public final class AdminCharacterIssuer implements AutoCloseable {
/** Must be entered on the server thread. Completion is delivered on that thread. */
public void issue(CommandSender sender, Player player, Consumer<Outcome> response) {
Objects.requireNonNull(sender); Objects.requireNonNull(player); Objects.requireNonNull(response);
if (closed || !player.isOnline()) { response.accept(Outcome.STALE); return; }
var action = adminAudit == null ? null : adminAudit.current();
if (closed || !player.isOnline()) {
audit(action, AdminActionEventBridge.Outcome.REFUSED, "stale", java.util.Map.of());
response.accept(Outcome.STALE); return;
}
int slot = player.getInventory().firstEmpty();
if (slot < 0) { response.accept(Outcome.FULL); return; }
var audit = identityEvents;
var attempt = new Attempt(player, slot, response, audit == null ? null : audit.issue(sender, player));
if (pending.putIfAbsent(attempt.playerId, attempt) != null) { response.accept(Outcome.BUSY); return; }
if (slot < 0) {
audit(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", java.util.Map.of());
response.accept(Outcome.FULL); return;
}
var attempt = new Attempt(player, slot, response, action);
if (pending.putIfAbsent(attempt.playerId, attempt) != null) {
audit(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", java.util.Map.of());
response.accept(Outcome.BUSY); return;
}
try {
var identity = identityEvents;
attempt.issue = identity == null ? null : identity.issue(sender, player);
attempt.record = allocate.get();
attempt.preparation = storage.prepareCraft(List.of(attempt.record),"admin_issue");
audit(action, AdminActionEventBridge.Outcome.PENDING, "owner_pending", java.util.Map.of());
attempt.preparation.ready().whenComplete((batch, failure) -> schedule(attempt, batch, failure));
} catch (RuntimeException failure) {
pending.remove(attempt.playerId, attempt);
abandon(attempt);
report(attempt, "prepare", failure);
auditOutcome(attempt, attempt.preparation == null ? Outcome.SAVE_FAILED : Outcome.RETAINED, null);
response.accept(Outcome.SAVE_FAILED);
}
}
@@ -63,13 +89,25 @@ public final class AdminCharacterIssuer implements AutoCloseable {
try { nextTick.accept(() -> complete(attempt, batch, failure)); }
catch (RuntimeException rejected) {
pending.remove(attempt.playerId, attempt); abandon(attempt); report(attempt, "schedule", rejected);
auditOutcome(attempt, Outcome.RETAINED, null);
}
}
private void complete(Attempt attempt, CharacterStorage.CraftBatch batch, Throwable failure) {
if (closed || !pending.remove(attempt.playerId, attempt)) { abandon(attempt); return; }
if (closed || !pending.remove(attempt.playerId, attempt)) {
abandon(attempt); auditOutcome(attempt, Outcome.RETAINED, null); return;
}
if (failure != null) {
abandon(attempt); report(attempt, "save", failure); respond(attempt, Outcome.SAVE_FAILED); return;
abandon(attempt);
report(attempt, "save", failure);
var cause = failure instanceof java.util.concurrent.CompletionException wrapper
? wrapper.getCause() : failure;
var provedRemoved = cause instanceof CharacterStorage.CraftPreparationException preparationFailure
&& preparationFailure.cleanup().retained().isEmpty();
auditOutcome(attempt, provedRemoved ? Outcome.SAVE_FAILED : Outcome.RETAINED, null);
try { attempt.response.accept(Outcome.SAVE_FAILED); }
catch (RuntimeException responseFailure) { report(attempt, "response", responseFailure); }
return;
}
var occupying = attempt.player.getInventory().getItem(attempt.slot);
if (!attempt.player.isOnline() || attempt.slot < 0 || attempt.slot >= 36
@@ -100,14 +138,39 @@ public final class AdminCharacterIssuer implements AutoCloseable {
catch (RuntimeException syncFailure) { report(attempt, "sync", syncFailure); }
var events = identityEvents;
if (events != null) events.issued(attempt.issue, attempt.player, savedRecord, attempt.slot);
auditOutcome(attempt, Outcome.DELIVERED, savedRecord);
respond(attempt, Outcome.DELIVERED);
}
private void respond(Attempt attempt, Outcome outcome) {
if (outcome != Outcome.DELIVERED) auditOutcome(attempt, outcome, null);
try { attempt.response.accept(outcome); }
catch (RuntimeException failure) { report(attempt, "response", failure); }
}
private void auditOutcome(Attempt attempt, Outcome outcome, CharacterRecord delivered) {
if (outcome == Outcome.DELIVERED && delivered != null) {
var facts = new java.util.LinkedHashMap<String, Object>();
if (attempt.issue != null) facts.put("domain_operation_id", attempt.issue.operation());
facts.put("subject_id", delivered.id());
facts.put("target_id", attempt.playerId);
audit(attempt.action, AdminActionEventBridge.Outcome.COMPLETED, "acknowledged", facts);
} else {
var classification = switch (outcome) {
case FULL, BUSY, STALE -> AdminActionEventBridge.Outcome.REFUSED;
case SAVE_FAILED -> AdminActionEventBridge.Outcome.FAILED;
case RETAINED -> AdminActionEventBridge.Outcome.UNCERTAIN;
case DELIVERED -> AdminActionEventBridge.Outcome.UNCERTAIN;
};
var reason = switch (classification) {
case REFUSED -> outcome == Outcome.STALE ? "stale" : "owner_refused";
case FAILED -> "operation_failed";
default -> "operation_uncertain";
};
audit(attempt.action, classification, reason, java.util.Map.of());
}
}
private void abandon(Attempt attempt) {
if (attempt.preparation == null || attempt.delivered || !attempt.abandoned.compareAndSet(false, true)) return;
attempt.preparation.abandon().thenAccept(cleanup -> {
@@ -123,18 +186,22 @@ public final class AdminCharacterIssuer implements AutoCloseable {
@Override public void close() {
closed = true;
for (var attempt : List.copyOf(pending.values())) {
if (pending.remove(attempt.playerId, attempt)) abandon(attempt);
if (pending.remove(attempt.playerId, attempt)) {
abandon(attempt);
auditOutcome(attempt, Outcome.RETAINED, null);
}
}
}
private static final class Attempt {
final Player player; final UUID playerId; final int slot; final Consumer<Outcome> response;
final games.dmg.fantasystick.events.CharacterIdentityEventBridge.Issue issue;
final AdminActionEventBridge.Action action;
games.dmg.fantasystick.events.CharacterIdentityEventBridge.Issue issue;
final java.util.concurrent.atomic.AtomicBoolean abandoned = new java.util.concurrent.atomic.AtomicBoolean();
CharacterRecord record; CharacterStorage.CraftPreparation preparation; volatile boolean delivered;
Attempt(Player player, int slot, Consumer<Outcome> response,
games.dmg.fantasystick.events.CharacterIdentityEventBridge.Issue issue) {
this.player=player; this.playerId=player.getUniqueId(); this.slot=slot; this.response=response; this.issue=issue;
AdminActionEventBridge.Action action) {
this.player=player; this.playerId=player.getUniqueId(); this.slot=slot; this.response=response; this.action=action;
}
}
}
@@ -1,5 +1,6 @@
package games.dmg.fantasystick.session;
import games.dmg.fantasystick.events.AdminActionEventBridge;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.persistence.CharacterStorage;
@@ -24,7 +25,7 @@ import org.bukkit.inventory.ItemStack;
public final class AdminCharacterRecovery implements Listener, AutoCloseable {
public record Failure(UUID character, UUID recipient, String operation, Throwable cause) { }
private record View(UUID nonce, Player administrator, Player recipient, CharacterRecord record,
int destination, Inventory inventory) { }
int destination, Inventory inventory, AdminActionEventBridge.Action action) { }
private record Prerequisites(java.util.Optional<CharacterRecord> record,
java.util.Optional<EquipmentSessionStore.State> receipt,
java.util.Optional<RevivalStore.Reservation> revival) { }
@@ -40,6 +41,17 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
private final Map<UUID, View> views = new ConcurrentHashMap<>();
private final CharacterSheets sheets = new CharacterSheets();
private volatile boolean closed;
private AdminActionEventBridge adminAudit;
public void attachAdminAudit(AdminActionEventBridge audit) {
if (closed || adminAudit != null) throw new IllegalStateException("Character recovery audit already attached");
adminAudit = Objects.requireNonNull(audit);
}
private void outcome(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome status,
String reason, Map<String, Object> facts) {
if (adminAudit != null) adminAudit.result(action, status, reason, facts);
}
public AdminCharacterRecovery(CharacterStorage characters, EquipmentSessionStore receipts,
RevivalStore revivals, EquipmentSessions sessions, Server server, Consumer<Runnable> nextTick,
@@ -59,6 +71,7 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
administrator.sendMessage("Character recovery refused: administrator or recipient is unavailable.");
return;
}
var action = adminAudit == null ? null : adminAudit.current();
UUID administratorId = administrator.getUniqueId();
UUID recipientId = recipient.getUniqueId();
Object ticket = new Object();
@@ -67,7 +80,7 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
characters.inspect(character).whenComplete((record, recordFailure) -> {
if (recordFailure != null) {
schedule(character, recipientId, () -> finishPreview(administratorId, ticket,
administrator, recipient, character, null, recordFailure));
administrator, recipient, character, null, recordFailure, action));
return;
}
try {
@@ -75,61 +88,67 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
receiptStage.whenComplete((receipt, receiptFailure) -> {
if (receiptFailure != null) {
schedule(character, recipientId, () -> finishPreview(administratorId, ticket,
administrator, recipient, character, null, receiptFailure));
administrator, recipient, character, null, receiptFailure, action));
return;
}
revivals.find(character).whenComplete((revival, revivalFailure) ->
schedule(character, recipientId, () -> finishPreview(administratorId, ticket,
administrator, recipient, character,
revivalFailure == null ? new Prerequisites(record, receipt, revival) : null,
revivalFailure)));
revivalFailure, action)));
});
} catch (RuntimeException rejected) {
schedule(character, recipientId, () -> finishPreview(administratorId, ticket,
administrator, recipient, character, null, rejected));
administrator, recipient, character, null, rejected, action));
}
});
}
private void finishPreview(UUID administratorId, Object ticket, Player administrator, Player recipient,
UUID character, Prerequisites loaded, Throwable failure) {
UUID character, Prerequisites loaded, Throwable failure, AdminActionEventBridge.Action action) {
if (closed || !pending.remove(administratorId, ticket)) return;
Player currentRecipient = server.getPlayer(recipient.getUniqueId());
if (!current(administrator) || currentRecipient != recipient || !recipient.isOnline()) {
outcome(action, AdminActionEventBridge.Outcome.REFUSED, "stale", Map.of());
administrator.sendMessage("Character recovery refused: administrator or recipient changed.");
return;
}
if (failure != null) {
report(character, recipient.getUniqueId(), "preview", failure);
outcome(action, AdminActionEventBridge.Outcome.FAILED, "operation_failed", Map.of());
administrator.sendMessage("Character recovery preview could not be loaded; no state changed.");
return;
}
var record = loaded.record().orElse(null);
if (record == null) {
outcome(action, AdminActionEventBridge.Outcome.REFUSED, "not_found", Map.of());
administrator.sendMessage("Character recovery refused: saved character not found.");
return;
}
if (loaded.receipt().map(EquipmentSessionStore.State::pending).orElse(null) != null
|| loaded.revival().isPresent()
|| !sessions.availableForCharacterRecovery(character, recipient.getUniqueId())) {
outcome(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", Map.of());
administrator.sendMessage("Character recovery refused: active or unresolved custody must be resolved first.");
return;
}
int destination = recipient.getInventory().firstEmpty();
if (destination < 0 || destination >= 36) {
outcome(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", Map.of());
administrator.sendMessage("Character recovery refused: recipient needs one empty main-inventory slot.");
return;
}
show(administrator, recipient, record, destination);
show(administrator, recipient, record, destination, action);
}
private void show(Player administrator, Player recipient, CharacterRecord record, int destination) {
private void show(Player administrator, Player recipient, CharacterRecord record, int destination,
AdminActionEventBridge.Action action) {
var inventory = server.createInventory(null, 9, Component.text("Recover saved character"));
inventory.setItem(2, action(record.dead() ? Material.BARRIER : Material.PAPER,
record.dead() ? "Living recovery unavailable" : "Recover living character sheet", record, recipient));
inventory.setItem(6, action(record.dead() ? Material.TOTEM_OF_UNDYING : Material.BARRIER,
record.dead() ? "Revive without Tail and recover sheet" : "No-Tail revival unavailable", record, recipient));
var view = new View(UUID.randomUUID(), administrator, recipient, record, destination, inventory);
var view = new View(UUID.randomUUID(), administrator, recipient, record, destination, inventory, action);
views.put(administrator.getUniqueId(), view);
administrator.openInventory(inventory);
}
@@ -164,6 +183,7 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
boolean revive = slot == 6;
if (!(slot == 2 || slot == 6) || revive != view.record().dead()) return;
if (!views.remove(administrator.getUniqueId(), view)) return;
if (adminAudit != null) adminAudit.confirmation(view.action(), current(administrator), "inventory_confirmation", null);
administrator.closeInventory();
confirm(view, revive);
}
@@ -173,11 +193,13 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
UUID recipientId = recipient.getUniqueId();
if (!current(administrator) || server.getPlayer(recipient.getUniqueId()) != recipient
|| !recipient.isOnline() || !empty(recipient, view.destination())) {
outcome(view.action(), AdminActionEventBridge.Outcome.REFUSED, "stale", Map.of());
administrator.sendMessage("Character recovery confirmation became stale; no state changed.");
return;
}
var custody = sessions.claimCharacterRecovery(view.record().id(), recipientId);
if (custody.isEmpty()) {
outcome(view.action(), AdminActionEventBridge.Outcome.REFUSED, "stale", Map.of());
administrator.sendMessage("Character recovery confirmation became stale; no state changed.");
return;
}
@@ -187,6 +209,7 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
catch (RuntimeException rejected) {
claim.close();
report(view.record().id(), recipientId, "receipt", rejected);
outcome(view.action(), AdminActionEventBridge.Outcome.FAILED, "operation_failed", Map.of());
administrator.sendMessage("Character recovery confirmation became stale; no state changed.");
return;
}
@@ -197,6 +220,8 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
|| !recipient.isOnline() || !empty(recipient, view.destination())) {
claim.close();
if (failure != null) report(view.record().id(), recipient.getUniqueId(), "receipt", failure);
outcome(view.action(), failure == null ? AdminActionEventBridge.Outcome.REFUSED
: AdminActionEventBridge.Outcome.FAILED, failure == null ? "stale" : "operation_failed", Map.of());
administrator.sendMessage("Character recovery confirmation became stale; no state changed.");
return;
}
@@ -207,6 +232,8 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
|| !empty(recipient, view.destination())) {
claim.close();
if (revivalFailure != null) report(view.record().id(), recipientId, "revival", revivalFailure);
outcome(view.action(), revivalFailure == null ? AdminActionEventBridge.Outcome.REFUSED
: AdminActionEventBridge.Outcome.FAILED, revivalFailure == null ? "stale" : "operation_failed", Map.of());
administrator.sendMessage("Character recovery confirmation became stale; no state changed.");
return;
}
@@ -216,20 +243,23 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
view.record().sheetGeneration(), revive, revive ? view.record().deathId() : null,
NativeHealthLimit.read());
characters.beginRecovery(request).whenComplete((commit, commitFailure) -> schedule(
view.record().id(), recipientId, () -> deliver(view, claim, commit, commitFailure)));
view.record().id(), recipientId, () -> deliver(view, claim, operation, commit, commitFailure)));
}));
}));
}
private void deliver(View view, EquipmentSessions.CharacterRecoveryClaim claim,
private void deliver(View view, EquipmentSessions.CharacterRecoveryClaim claim, UUID operation,
CharacterStorage.RecoveryCommit commit, Throwable failure) {
if (failure != null) {
report(view.record().id(), view.recipient().getUniqueId(), "commit", failure);
outcome(view.action(), AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain",
Map.of("domain_operation_id", operation));
view.administrator().sendMessage("Character recovery failed or is retained for inspection; no retry was performed.");
return;
}
if (commit.status() != CharacterStorage.RecoveryStatus.APPLIED || commit.record().isEmpty()) {
claim.close();
outcome(view.action(), AdminActionEventBridge.Outcome.REFUSED, "stale", Map.of());
view.administrator().sendMessage("Character recovery refused: saved state or custody changed ("
+ commit.status().name().toLowerCase(java.util.Locale.ROOT) + ").");
return;
@@ -238,6 +268,8 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
Player recipient = view.recipient();
if (!current(view.administrator()) || server.getPlayer(recipient.getUniqueId()) != recipient || !recipient.isOnline()
|| !empty(recipient, view.destination())) {
outcome(view.action(), AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain",
Map.of("domain_operation_id", commit.operation()));
view.administrator().sendMessage("Character recovery committed, but native delivery is uncertain; do not retry blindly.");
return;
}
@@ -247,6 +279,8 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
throw new IllegalStateException("Native inventory did not retain the recovered sheet");
} catch (RuntimeException uncertain) {
report(record.id(), recipient.getUniqueId(), "native-delivery", uncertain);
outcome(view.action(), AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain",
Map.of("domain_operation_id", commit.operation()));
view.administrator().sendMessage("Character recovery committed, but native delivery is uncertain; do not retry blindly.");
return;
}
@@ -257,10 +291,16 @@ public final class AdminCharacterRecovery implements Listener, AutoCloseable {
schedule(record.id(), recipientId, () -> {
if (completionFailure != null || !completed) {
if (completionFailure != null) report(record.id(), recipient.getUniqueId(), "completion", completionFailure);
outcome(view.action(), AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain",
Map.of("domain_operation_id", commit.operation()));
view.administrator().sendMessage("Recovery sheet was delivered, but durable completion is retained for inspection.");
return;
}
claim.close();
outcome(view.action(), AdminActionEventBridge.Outcome.COMPLETED, "acknowledged",
Map.of("domain_operation_id", commit.operation(), "subject_id", record.id(),
"target_id", recipientId, "revision_before", view.record().revision().toString(),
"revision_after", record.revision().toString()));
if (current(view.administrator())) view.administrator().sendMessage(
(view.record().dead() ? "Revived without a Tail and recovered " : "Recovered ")
+ record.name() + " for " + recipient.getName() + ". Older sheets are revoked.");
@@ -1,5 +1,6 @@
package games.dmg.fantasystick.session;
import games.dmg.fantasystick.events.AdminActionEventBridge;
import games.dmg.fantasystick.events.AdminExperienceEventBridge;
import games.dmg.fantasystick.persistence.CharacterRecord;
import games.dmg.fantasystick.persistence.CharacterStorage;
@@ -30,17 +31,28 @@ public final class AdminExperienceGrant implements AutoCloseable {
private final games.dmg.fantasystick.presentation.ParticleDelivery particles;
private volatile boolean closed;
private AdminExperienceEventBridge events;
private AdminActionEventBridge adminAudit;
public void attachAdminAudit(AdminActionEventBridge audit) {
if (closed || adminAudit != null) throw new IllegalStateException("Experience grant audit already attached");
adminAudit = Objects.requireNonNull(audit);
}
private final java.util.concurrent.ConcurrentMap<UUID, Pending> pending = new java.util.concurrent.ConcurrentHashMap<>();
private static final class Pending {
final AdminExperienceEventBridge.Intent intent;
final AdminActionEventBridge.Action action;
final UUID targetPlayer;
final CharacterRecord captured;
final BigInteger amount;
CharacterStorage.ExperienceAward award;
boolean saveFailed;
boolean resolved;
boolean emitted;
Pending(AdminExperienceEventBridge.Intent intent, CharacterRecord captured, BigInteger amount) {
this.intent = intent; this.captured = captured; this.amount = amount;
Pending(AdminExperienceEventBridge.Intent intent, AdminActionEventBridge.Action action,
UUID targetPlayer, CharacterRecord captured, BigInteger amount) {
this.intent = intent; this.action = action; this.targetPlayer = targetPlayer;
this.captured = captured; this.amount = amount;
}
}
@@ -77,8 +89,12 @@ public final class AdminExperienceGrant implements AutoCloseable {
Objects.requireNonNull(active); Objects.requireNonNull(captured);
Objects.requireNonNull(amount); Objects.requireNonNull(completion);
if (amount.signum() <= 0) throw new IllegalArgumentException("Experience grant must be positive");
var action = adminAudit == null ? null : adminAudit.current();
if (closed || !sessions.current(active)
|| sessions.currentRecord(active).filter(captured::equals).isEmpty()) return false;
|| sessions.currentRecord(active).filter(captured::equals).isEmpty()) {
audit(action, AdminActionEventBridge.Outcome.REFUSED, "stale", java.util.Map.of());
return false;
}
AdminExperienceEventBridge.Intent intent = null;
if (events != null && administrator != null) {
Player target = null;
@@ -87,17 +103,30 @@ public final class AdminExperienceGrant implements AutoCloseable {
try { intent = events.capture(administrator, active, captured, target); }
catch (RuntimeException failure) { report(captured.id(), failure); }
}
var operation = new Pending(intent, captured, amount);
var operation = new Pending(intent, action, active.player(), captured, amount);
if (intent != null) pending.put(intent.operation(), operation);
characters.awardExperience(captured.id(), captured.revision(), amount, progression)
.whenComplete((award, failure) -> schedule(active, operation, completion, award, failure));
audit(action, AdminActionEventBridge.Outcome.PENDING, "owner_pending", java.util.Map.of());
try {
characters.awardExperience(captured.id(), captured.revision(), amount, progression)
.whenComplete((award, failure) -> schedule(active, operation, completion, award, failure));
} catch (RuntimeException failure) {
report(captured.id(), failure);
// An exception from the storage port cannot prove whether its write was accepted.
audit(action, AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", java.util.Map.of());
if (intent != null) pending.remove(intent.operation(), operation);
throw failure;
}
return true;
}
private void schedule(EquipmentSessions.Active active, Pending operation,
Consumer<Result> completion, CharacterStorage.ExperienceAward award, Throwable failure) {
if (failure != null) report(operation.captured.id(), failure);
synchronized (operation) { operation.award = award; operation.resolved = true; }
synchronized (operation) {
operation.award = award;
operation.saveFailed = failure != null;
operation.resolved = true;
}
if (closed) { publish(operation, false); return; }
try {
nextTick.accept(() -> complete(active, operation, completion, award, failure));
@@ -149,14 +178,40 @@ public final class AdminExperienceGrant implements AutoCloseable {
if (!operation.resolved) return; // A later worker completion will observe close and retain the intent.
operation.emitted = true;
if (award != null && award.status() == CharacterStorage.ExperienceAwardStatus.APPLIED
&& award.record().isPresent() && events != null) {
events.granted(operation.intent, operation.captured, award.record().orElseThrow(),
&& award.record().isPresent()) {
var saved = award.record().orElseThrow();
if (events != null) events.granted(operation.intent, operation.captured, saved,
operation.amount, award.levels(), feedbackDelivered);
var facts = new java.util.LinkedHashMap<String, Object>();
if (operation.intent != null) facts.put("domain_operation_id", operation.intent.operation());
facts.put("subject_id", saved.id());
facts.put("target_id", operation.targetPlayer);
facts.put("requested", operation.amount.toString());
facts.put("applied", saved.experience().subtract(operation.captured.experience()).toString());
audit(operation.action, AdminActionEventBridge.Outcome.COMPLETED, "acknowledged", facts);
} else if (award == null) {
audit(operation.action, operation.saveFailed ? AdminActionEventBridge.Outcome.FAILED
: AdminActionEventBridge.Outcome.UNCERTAIN,
operation.saveFailed ? "operation_failed" : "operation_uncertain", java.util.Map.of());
} else {
var outcome = switch (award.status()) {
case AT_CAP, UNCHANGED, STALE, UNAVAILABLE -> AdminActionEventBridge.Outcome.REFUSED;
case APPLIED -> AdminActionEventBridge.Outcome.UNCERTAIN;
};
audit(operation.action, outcome, outcome == AdminActionEventBridge.Outcome.UNCERTAIN
? "operation_uncertain" : award.status() == CharacterStorage.ExperienceAwardStatus.STALE
? "stale" : "owner_refused", java.util.Map.of());
}
}
if (operation.intent != null) pending.remove(operation.intent.operation(), operation);
}
private void audit(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome outcome,
String reason, java.util.Map<String, Object> facts) {
var bridge = adminAudit;
if (bridge != null) bridge.result(action, outcome, reason, facts);
}
private boolean feedback(EquipmentSessions.Active active, CharacterRecord saved, BigInteger applied, int levels) {
Player player;
try { player = players.apply(active.player()); }
@@ -1,5 +1,6 @@
package games.dmg.fantasystick.session;
import games.dmg.fantasystick.events.AdminActionEventBridge;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.items.TailBooks;
import games.dmg.fantasystick.persistence.CharacterRecord;
@@ -37,6 +38,17 @@ public final class AdminRevival implements Listener, AutoCloseable {
private final Consumer<Throwable> failures; private final TailBooks tails=new TailBooks();private final CharacterSheets sheets=new CharacterSheets();
private final Map<Inventory,View> views=new IdentityHashMap<>();private boolean closed;
private games.dmg.fantasystick.events.AdminRevivalEventBridge auditEvents;
private AdminActionEventBridge adminAudit;
public void attachAdminAudit(AdminActionEventBridge audit) {
if (closed || adminAudit != null) throw new IllegalStateException("Admin revival audit already attached");
adminAudit = Objects.requireNonNull(audit);
}
private void outcome(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome status,
String reason, Map<String, Object> facts) {
if (adminAudit != null) adminAudit.result(action, status, reason, facts);
}
public void attachEvents(games.dmg.fantasystick.events.AdminRevivalEventBridge events) {
if (closed || auditEvents != null) throw new IllegalStateException("Admin revival events already attached");
@@ -44,30 +56,30 @@ public final class AdminRevival implements Listener, AutoCloseable {
}
private final class View implements AutoCloseable {
final Player admin,target;final Inventory inventory;final Map<Integer,Choice> choices;final Instant deadline;final AutoCloseable expiry;boolean selecting,finished;
View(Player admin,Player target,Inventory inventory,Map<Integer,Choice> choices,Instant deadline){this.admin=admin;this.target=target;this.inventory=inventory;this.choices=choices;this.deadline=deadline;this.expiry=scheduler.later(Duration.between(clock.instant(),deadline),this::close);}
final Player admin,target;final Inventory inventory;final Map<Integer,Choice> choices;final Instant deadline;final AutoCloseable expiry;final AdminActionEventBridge.Action action;boolean selecting,finished;
View(Player admin,Player target,Inventory inventory,Map<Integer,Choice> choices,Instant deadline,AdminActionEventBridge.Action action){this.admin=admin;this.target=target;this.inventory=inventory;this.choices=choices;this.deadline=deadline;this.action=action;this.expiry=scheduler.later(Duration.between(clock.instant(),deadline),this::close);}
boolean current(){return !closed&&!finished&&admin.isOnline()&&admin.hasPermission(EquipmentAdminCommand.PERMISSION)&&target.isOnline()&&clock.instant().isBefore(deadline);}
@Override public void close(){if(finished)return;finished=true;views.remove(inventory,this);inventory.clear();try{expiry.close();}catch(Exception e){report(e);}try{admin.closeInventory();}catch(RuntimeException e){report(e);}}
}
public AdminRevival(CharacterStorage characters,RevivalStore reservations,Clock clock,Consumer<Runnable> nextTick,Scheduler scheduler,PopupFactory popups,Consumer<Throwable> failures){this.characters=Objects.requireNonNull(characters);this.reservations=Objects.requireNonNull(reservations);this.clock=Objects.requireNonNull(clock);this.nextTick=Objects.requireNonNull(nextTick);this.scheduler=Objects.requireNonNull(scheduler);this.popups=Objects.requireNonNull(popups);this.failures=Objects.requireNonNull(failures);}
public void open(Player admin,Player target,Duration timeout){Objects.requireNonNull(admin);Objects.requireNonNull(target);if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline()){admin.sendMessage("Admin revival refused: authorization or target is no longer available.");return;}var candidates=candidates(target);if(candidates.isEmpty()){admin.sendMessage("That player has no authentic direct-inventory Tails.");return;}var loads=candidates.stream().map(c->characters.find(c.identity.characterId())).toList();CompletableFuture.allOf(loads.toArray(CompletableFuture[]::new)).whenComplete((ignored,failure)->schedule(()->{if(failure!=null){report(failure);admin.sendMessage("Admin revival could not inspect those Tails safely.");return;}if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline())return;var choices=new ArrayList<Choice>();for(int i=0;i<candidates.size();i++){var found=loads.get(i).join();if(found.isPresent()&&eligible(found.orElseThrow(),candidates.get(i).identity)&&unchanged(target,candidates.get(i)))choices.add(new Choice(candidates.get(i),found.orElseThrow()));}if(choices.isEmpty()){admin.sendMessage("That player has no current unconsumed Tail.");return;}show(admin,target,choices,timeout);}));}
public void open(Player admin,Player target,Duration timeout){Objects.requireNonNull(admin);Objects.requireNonNull(target);if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline()){admin.sendMessage("Admin revival refused: authorization or target is no longer available.");return;}var candidates=candidates(target);if(candidates.isEmpty()){admin.sendMessage("That player has no authentic direct-inventory Tails.");return;}var action=adminAudit==null?null:adminAudit.current();var loads=candidates.stream().map(c->characters.find(c.identity.characterId())).toList();CompletableFuture.allOf(loads.toArray(CompletableFuture[]::new)).whenComplete((ignored,failure)->schedule(()->{if(failure!=null){report(failure);admin.sendMessage("Admin revival could not inspect those Tails safely.");return;}if(closed||!admin.isOnline()||!admin.hasPermission(EquipmentAdminCommand.PERMISSION)||!target.isOnline())return;var choices=new ArrayList<Choice>();for(int i=0;i<candidates.size();i++){var found=loads.get(i).join();if(found.isPresent()&&eligible(found.orElseThrow(),candidates.get(i).identity)&&unchanged(target,candidates.get(i)))choices.add(new Choice(candidates.get(i),found.orElseThrow()));}if(choices.isEmpty()){admin.sendMessage("That player has no current unconsumed Tail.");return;}show(admin,target,choices,timeout,action);}));}
private List<Candidate> candidates(Player target){var result=new ArrayList<Candidate>();for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40)continue;var item=target.getInventory().getItem(slot);if(item==null||item.isEmpty())continue;var identity=tails.identify(item);if(identity.isPresent())result.add(new Candidate(slot,item.clone(),identity.orElseThrow()));}return List.copyOf(result);}
private boolean eligible(CharacterRecord record,TailBooks.Identity id){return record.dead()&&record.id().equals(id.characterId())&&Objects.equals(record.deathId(),id.deathId())&&!record.diedAt().isAfter(clock.instant());}
private static boolean unchanged(Player target,Candidate candidate){var item=target.getInventory().getItem(candidate.slot);return item!=null&&item.equals(candidate.item);}
private void show(Player admin,Player target,List<Choice> eligible,Duration timeout){int size=Math.min(54,Math.max(9,((eligible.size()+8)/9)*9));var inventory=popups.create(size,Component.text("Choose a Tail for "+target.getName()));var choices=new LinkedHashMap<Integer,Choice>();for(int i=0;i<eligible.size()&&i<size;i++){var choice=eligible.get(i);var item=choice.candidate.item.clone();item.setAmount(1);var meta=item.getItemMeta();meta.lore(List.of(Component.text("Character: "+choice.record.name()),Component.text("Level "+choice.record.level()+" · target slot "+choice.candidate.slot),Component.text("Click to restore this exact death")));item.setItemMeta(meta);inventory.setItem(i,item);choices.put(i,choice);}var view=new View(admin,target,inventory,Map.copyOf(choices),clock.instant().plus(timeout));views.put(inventory,view);admin.openInventory(inventory);}
private void show(Player admin,Player target,List<Choice> eligible,Duration timeout,AdminActionEventBridge.Action action){int size=Math.min(54,Math.max(9,((eligible.size()+8)/9)*9));var inventory=popups.create(size,Component.text("Choose a Tail for "+target.getName()));var choices=new LinkedHashMap<Integer,Choice>();for(int i=0;i<eligible.size()&&i<size;i++){var choice=eligible.get(i);var item=choice.candidate.item.clone();item.setAmount(1);var meta=item.getItemMeta();meta.lore(List.of(Component.text("Character: "+choice.record.name()),Component.text("Level "+choice.record.level()+" · target slot "+choice.candidate.slot),Component.text("Click to restore this exact death")));item.setItemMeta(meta);inventory.setItem(i,item);choices.put(i,choice);}var view=new View(admin,target,inventory,Map.copyOf(choices),clock.instant().plus(timeout),action);views.put(inventory,view);admin.openInventory(inventory);}
@EventHandler(priority=EventPriority.HIGHEST) public void click(org.bukkit.event.inventory.InventoryClickEvent event){var view=views.get(event.getView().getTopInventory());if(view==null)return;event.setCancelled(true);if(event.getWhoClicked()!=view.admin||event.getRawSlot()<0||event.getRawSlot()>=view.inventory.getSize())return;var choice=view.choices.get(event.getRawSlot());if(choice==null||view.selecting)return;view.selecting=true;views.remove(view.inventory,view);view.inventory.clear();view.admin.closeInventory();confirm(view,choice);}
@EventHandler(priority=EventPriority.HIGHEST) public void click(org.bukkit.event.inventory.InventoryClickEvent event){var view=views.get(event.getView().getTopInventory());if(view==null)return;event.setCancelled(true);if(event.getWhoClicked()!=view.admin||event.getRawSlot()<0||event.getRawSlot()>=view.inventory.getSize())return;var choice=view.choices.get(event.getRawSlot());if(choice==null||view.selecting)return;view.selecting=true;views.remove(view.inventory,view);if(adminAudit!=null)adminAudit.confirmation(view.action,view.admin.isOnline()&&view.admin.hasPermission(EquipmentAdminCommand.PERMISSION),"inventory_confirmation",null);view.inventory.clear();view.admin.closeInventory();confirm(view,choice);}
@EventHandler(priority=EventPriority.HIGHEST) public void drag(org.bukkit.event.inventory.InventoryDragEvent event){var view=views.get(event.getView().getTopInventory());if(view!=null&&event.getRawSlots().stream().anyMatch(slot->slot<view.inventory.getSize()))event.setCancelled(true);}
@EventHandler(priority=EventPriority.MONITOR) public void close(org.bukkit.event.inventory.InventoryCloseEvent event){var view=views.get(event.getView().getTopInventory());if(view!=null&&!view.selecting)view.close();}
@EventHandler(priority=EventPriority.MONITOR) public void quit(org.bukkit.event.player.PlayerQuitEvent event){for(var view:List.copyOf(views.values()))if(view.admin==event.getPlayer()||view.target==event.getPlayer())view.close();}
private void confirm(View view,Choice choice){if(!view.current()||!unchanged(view.target,choice.candidate)){view.close();return;}characters.find(choice.record.id()).whenComplete((found,failure)->schedule(()->{if(failure!=null){report(failure);view.admin.sendMessage("Admin revival could not recheck that Tail; no item changed.");view.close();return;}if(!view.current()||found.isEmpty()||!eligible(found.orElseThrow(),choice.candidate.identity)||!unchanged(view.target,choice.candidate)){view.admin.sendMessage("That Tail selection is stale; no item changed.");view.close();return;}reserve(view,choice.candidate,found.orElseThrow());}));}
private void reserve(View view,Candidate candidate,CharacterRecord dead){var source=view.target.getInventory().getItem(candidate.slot);int destination=source.getAmount()==1?-1:emptySlot(view.target,candidate.slot);if(source.getAmount()>1&&destination<0){view.admin.sendMessage("Admin revival needs one empty direct inventory slot to preserve copied Tails.");view.close();return;}var reservation=new RevivalStore.Reservation(UUID.randomUUID(),view.admin.getUniqueId(),view.target.getUniqueId(),dead.id(),dead.deathId(),clock.instant().truncatedTo(ChronoUnit.SECONDS),candidate.slot,source.getAmount(),destination,true);var audit=auditEvents==null?null:auditEvents.selection(view.admin,view.target);reservations.reserve(reservation).whenComplete((saved,failure)->schedule(()->{if(failure!=null){report(failure);view.admin.sendMessage("Admin revival reservation failed; no item changed.");view.close();return;}if(saved.isEmpty()||!view.current()||!unchanged(view.target,candidate)){view.admin.sendMessage("Admin revival became stale after reservation; no item changed.");view.close();return;}deliver(view,dead,reservation,audit);}));}
private void confirm(View view,Choice choice){if(!view.current()||!unchanged(view.target,choice.candidate)){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"stale",Map.of());view.close();return;}characters.find(choice.record.id()).whenComplete((found,failure)->schedule(()->{if(failure!=null){report(failure);outcome(view.action,AdminActionEventBridge.Outcome.FAILED,"operation_failed",Map.of());view.admin.sendMessage("Admin revival could not recheck that Tail; no item changed.");view.close();return;}if(!view.current()||found.isEmpty()||!eligible(found.orElseThrow(),choice.candidate.identity)||!unchanged(view.target,choice.candidate)){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"stale",Map.of());view.admin.sendMessage("That Tail selection is stale; no item changed.");view.close();return;}reserve(view,choice.candidate,found.orElseThrow());}));}
private void reserve(View view,Candidate candidate,CharacterRecord dead){var source=view.target.getInventory().getItem(candidate.slot);int destination=source.getAmount()==1?-1:emptySlot(view.target,candidate.slot);if(source.getAmount()>1&&destination<0){outcome(view.action,AdminActionEventBridge.Outcome.REFUSED,"owner_refused",Map.of());view.admin.sendMessage("Admin revival needs one empty direct inventory slot to preserve copied Tails.");view.close();return;}var reservation=new RevivalStore.Reservation(UUID.randomUUID(),view.admin.getUniqueId(),view.target.getUniqueId(),dead.id(),dead.deathId(),clock.instant().truncatedTo(ChronoUnit.SECONDS),candidate.slot,source.getAmount(),destination,true);var audit=auditEvents==null?null:auditEvents.selection(view.admin,view.target);reservations.reserve(reservation).whenComplete((saved,failure)->schedule(()->{if(failure!=null){report(failure);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival reservation failed; no item changed.");view.close();return;}if(saved.isEmpty()||!view.current()||!unchanged(view.target,candidate)){outcome(view.action,saved.isEmpty()?AdminActionEventBridge.Outcome.REFUSED:AdminActionEventBridge.Outcome.UNCERTAIN,saved.isEmpty()?"stale":"operation_uncertain",saved.isEmpty()?Map.of():Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival became stale after reservation; no item changed.");view.close();return;}deliver(view,dead,reservation,audit);}));}
private static int emptySlot(Player target,int source){for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40||slot==source)continue;var item=target.getInventory().getItem(slot);if(item==null||item.isEmpty())return slot;}return-1;}
private void deliver(View view,CharacterRecord dead,RevivalStore.Reservation reservation,games.dmg.fantasystick.events.AdminRevivalEventBridge.Selection audit){try{var provisional=new CharacterRecord(dead.id(),dead.name(),dead.revision(),dead.stats(),dead.level(),dead.experience(),dead.unspentPoints(),dead.maximumHealth(),dead.learned(),dead.loadout(),dead.passives(),dead.cooldowns(),dead.restrictedKills(),false,dead.deathId(),dead.diedAt(),dead.sheetGeneration());var sheet=sheets.create(provisional);var source=view.target.getInventory().getItem(reservation.sourceSlot());if(reservation.sourceAmount()==1)view.target.getInventory().setItem(reservation.sourceSlot(),sheet);else{view.target.getInventory().setItem(reservation.destinationSlot(),sheet);var remaining=source.clone();remaining.setAmount(reservation.sourceAmount()-1);view.target.getInventory().setItem(reservation.sourceSlot(),remaining);}view.target.updateInventory();}catch(RuntimeException uncertain){report(uncertain);view.admin.sendMessage("Admin revival delivery is uncertain; retained proof requires recovery.");view.close();return;}characters.restoreDeathRecordAdministratively(reservation.character(),reservation.death(),NativeHealthLimit.read()).whenComplete((restored,failure)->schedule(()->{if(failure!=null||restored.isEmpty()){if(failure!=null)report(failure);view.admin.sendMessage("The Tail changed, but restoration is pending proof-based recovery.");view.close();return;}if(installFinal(view.target,restored.orElseThrow())){if(auditEvents!=null)auditEvents.revived(audit,reservation,dead,restored.orElseThrow(),view.target);reservations.clear(reservation.character(),reservation.id()).exceptionally(error->{report(error);return false;});view.admin.sendMessage("Administratively restored "+restored.orElseThrow().name()+" for "+view.target.getName()+".");view.target.sendMessage("An administrator restored character sheet: "+restored.orElseThrow().name()+".");}else view.admin.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");view.close();}));}
private boolean installFinal(Player target,CharacterRecord record){int found=-1;for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40)continue;if(sheets.identify(target.getInventory().getItem(slot)).filter(record.id()::equals).isEmpty())continue;if(found>=0)return false;found=slot;}if(found<0)return false;target.getInventory().setItem(found,sheets.create(record));target.updateInventory();return true;}
private void deliver(View view,CharacterRecord dead,RevivalStore.Reservation reservation,games.dmg.fantasystick.events.AdminRevivalEventBridge.Selection audit){try{var provisional=new CharacterRecord(dead.id(),dead.name(),dead.revision(),dead.stats(),dead.level(),dead.experience(),dead.unspentPoints(),dead.maximumHealth(),dead.learned(),dead.loadout(),dead.passives(),dead.cooldowns(),dead.restrictedKills(),false,dead.deathId(),dead.diedAt(),dead.sheetGeneration());var sheet=sheets.create(provisional);var source=view.target.getInventory().getItem(reservation.sourceSlot());if(reservation.sourceAmount()==1)view.target.getInventory().setItem(reservation.sourceSlot(),sheet);else{view.target.getInventory().setItem(reservation.destinationSlot(),sheet);var remaining=source.clone();remaining.setAmount(reservation.sourceAmount()-1);view.target.getInventory().setItem(reservation.sourceSlot(),remaining);}view.target.updateInventory();}catch(RuntimeException uncertain){report(uncertain);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Admin revival delivery is uncertain; retained proof requires recovery.");view.close();return;}characters.restoreDeathRecordAdministratively(reservation.character(),reservation.death(),NativeHealthLimit.read()).whenComplete((restored,failure)->schedule(()->{if(failure!=null||restored.isEmpty()){if(failure!=null)report(failure);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("The Tail changed, but restoration is pending proof-based recovery.");view.close();return;}boolean installed;try{installed=installFinal(view.target,restored.orElseThrow());}catch(RuntimeException uncertain){report(uncertain);outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");view.close();return;}if(installed){if(auditEvents!=null)auditEvents.revived(audit,reservation,dead,restored.orElseThrow(),view.target);reservations.clear(reservation.character(),reservation.id()).exceptionally(error->{report(error);return false;});outcome(view.action,AdminActionEventBridge.Outcome.COMPLETED,"acknowledged",Map.of("domain_operation_id",reservation.id(),"subject_id",dead.id(),"target_id",view.target.getUniqueId()));view.admin.sendMessage("Administratively restored "+restored.orElseThrow().name()+" for "+view.target.getName()+".");view.target.sendMessage("An administrator restored character sheet: "+restored.orElseThrow().name()+".");}else{outcome(view.action,AdminActionEventBridge.Outcome.UNCERTAIN,"operation_uncertain",Map.of("domain_operation_id",reservation.id()));view.admin.sendMessage("Character restoration was saved, but sheet custody is ambiguous; retained proof requires recovery.");}view.close();}));}
private boolean installFinal(Player target,CharacterRecord record){int found=-1;for(int slot=0;slot<=40;slot++){if(slot>35&&slot!=40)continue;if(sheets.identify(target.getInventory().getItem(slot)).filter(record.id()::equals).isEmpty())continue;if(found>=0)return false;found=slot;}if(found<0)return false;target.getInventory().setItem(found,sheets.create(record));target.updateInventory();return sheets.authorizes(target.getInventory().getItem(found),record);}
private void schedule(Runnable action){try{nextTick.accept(action);}catch(RuntimeException rejected){report(rejected);}}
private void report(Throwable failure){try{failures.accept(failure);}catch(RuntimeException ignored){}}
@Override public void close(){if(closed)return;closed=true;for(var view:List.copyOf(views.values()))view.close();views.clear();}
@@ -20,7 +20,9 @@ import org.bukkit.plugin.Plugin;
public final class DownedController implements Listener,AutoCloseable{
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 final java.util.Set<UUID> endedProtection=new java.util.HashSet<>();private games.dmg.fantasystick.events.DownedEventBridge events;private games.dmg.fantasystick.shop.PhoenixDownService phoenix;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 record FloatingCount(Object connection,java.lang.reflect.Field field,int prior){}
private record Freeze(Player player,boolean gravity,FloatingCount floating){}
private final java.util.Map<UUID,Freeze> gravity=new java.util.HashMap<>();private final java.util.Set<UUID> endedProtection=new java.util.HashSet<>();private games.dmg.fantasystick.events.DownedEventBridge events;private games.dmg.fantasystick.shop.PhoenixDownService phoenix;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 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 attachPhoenix(games.dmg.fantasystick.shop.PhoenixDownService phoenix){if(pulse!=null||this.phoenix!=null)throw new IllegalStateException("Phoenix Down already attached or controller installed");this.phoenix=Objects.requireNonNull(phoenix);}
@@ -32,8 +34,40 @@ public final class DownedController implements Listener,AutoCloseable{
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());}
private void freeze(Player player){
gravity.computeIfAbsent(player.getUniqueId(),ignored->new Freeze(player,player.hasGravity(),captureFloating(player)));
player.setGravity(false);player.setFallDistance(0);player.setVelocity(new org.bukkit.util.Vector());if(player.isInsideVehicle())player.leaveVehicle();
}
private static Object connection(Player player)throws ReflectiveOperationException{
var handle=player.getClass().getMethod("getHandle").invoke(player);
return handle==null?null:handle.getClass().getField("connection").get(handle);
}
private FloatingCount captureFloating(Player player){
try{
var connection=connection(player);if(connection==null)return null;
Class<?> type=connection.getClass();java.lang.reflect.Field field=null;
while(type!=null){try{field=type.getDeclaredField("aboveGroundTickCount");break;}catch(NoSuchFieldException absent){type=type.getSuperclass();}}
if(field==null)throw new NoSuchFieldException("Pinned native player floating count unavailable");
field.setAccessible(true);return new FloatingCount(connection,field,field.getInt(connection));
}catch(NoSuchMethodException unavailable){return null;/* Non-native API adapter has no connection to own. */}
catch(ReflectiveOperationException|RuntimeException unavailable){report(unavailable);return null;}
}
private void release(Player player){
var original=gravity.get(player.getUniqueId());
if(original==null||original.player()!=player)return;
gravity.remove(player.getUniqueId(),original);
if(player.hasGravity())return;/* An intervening gravity change is not ours to undo. */
var floating=original.floating();
if(original.gravity()&&floating!=null){
try{
if(connection(player)==floating.connection()){
int current=floating.field().getInt(floating.connection());
if(current>floating.prior())floating.field().setInt(floating.connection(),floating.prior());
}
}catch(ReflectiveOperationException|RuntimeException unavailable){report(unavailable);}
}
player.setGravity(original.gravity());
}
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&&!"phoenix_down".equals(resolved.decision()==null?null:resolved.decision().source())){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);}}));}
@@ -55,8 +89,9 @@ public final class DownedController implements Listener,AutoCloseable{
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void effect(org.bukkit.event.entity.EntityPotionEffectEvent event){if(event.getEntity() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void vehicle(org.bukkit.event.vehicle.VehicleEnterEvent event){if(event.getEntered() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void flight(org.bukkit.event.player.PlayerToggleFlightEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
@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());}});}
/** Native slot cache notifications are observations, not inventory-action or rollback authority. */
@EventHandler(priority=EventPriority.MONITOR)public void slot(io.papermc.paper.event.player.PlayerInventorySlotChangeEvent event){/* Actual actions are cancelled at their input boundaries; never replay cached old stacks. */}
@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();endedProtection.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();endedProtection.clear();}
}
File diff suppressed because it is too large. Load diff
@@ -54,6 +54,7 @@ public final class EquipmentSessions implements AutoCloseable {
private games.dmg.fantasystick.events.CharacterIdentityEventBridge identityEvents;
private games.dmg.fantasystick.events.EquipmentEventBridge equipmentEvents;
private games.dmg.fantasystick.events.SessionRecoveryEventBridge sessionRecoveryEvents;
private games.dmg.fantasystick.events.AdminActionEventBridge adminAudit;
private java.util.function.Function<DownedEpisode,CompletionStage<?>> downedDefeatRewards=ignored->CompletableFuture.completedStage(null);
private java.util.function.Predicate<UUID> unavailableCharacter = ignored -> false;
private java.util.function.Function<UUID,java.util.concurrent.CompletionStage<?>> partyDefeat =
@@ -116,6 +117,8 @@ public final class EquipmentSessions implements AutoCloseable {
boolean healthAcknowledged = true;
boolean nativeRestored;
boolean gearRestoredForModeRecovery;
boolean restorationRefused;
boolean receiptUncertain;
boolean presentationInstalled;
boolean cleaning;
boolean cleanupAttempted;
@@ -136,6 +139,7 @@ public final class EquipmentSessions implements AutoCloseable {
games.dmg.fantasystick.events.EquipmentEventBridge.Action restoreAction;
games.dmg.fantasystick.events.EquipmentEventBridge.Action recoveryAction;
games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action sessionRecoveryAction;
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminRecoveryAction;
games.dmg.fantasystick.events.EventInput.Location recoveryOriginalLocation;
games.dmg.fantasystick.events.EventInput.Location recoveryCurrentLocation;
String recoveryPriorPhase = "unavailable";
@@ -145,6 +149,7 @@ public final class EquipmentSessions implements AutoCloseable {
boolean restoreEventWritten;
Duration exitDelay;
boolean arrival;
boolean completedDeathRead;
Attempt recoveryOwner;
org.bukkit.Location entryLocation;
boolean defeated;
@@ -242,6 +247,7 @@ public final class EquipmentSessions implements AutoCloseable {
public synchronized void attachIdentityEvents(games.dmg.fantasystick.events.CharacterIdentityEventBridge events){if(!owned.isEmpty()||identityEvents!=null)throw new IllegalStateException("Identity events already attached or sessions started");identityEvents=Objects.requireNonNull(events);}
public synchronized void attachEquipmentEvents(games.dmg.fantasystick.events.EquipmentEventBridge events){if(!owned.isEmpty()||equipmentEvents!=null)throw new IllegalStateException("Equipment events already attached or sessions started");equipmentEvents=Objects.requireNonNull(events);}
public synchronized void attachSessionRecoveryEvents(games.dmg.fantasystick.events.SessionRecoveryEventBridge events){if(!owned.isEmpty()||sessionRecoveryEvents!=null)throw new IllegalStateException("Recovery events already attached or sessions started");sessionRecoveryEvents=Objects.requireNonNull(events);}
public synchronized void attachAdminAudit(games.dmg.fantasystick.events.AdminActionEventBridge audit){if(closed||adminAudit!=null)throw new IllegalStateException("Admin audit already attached or sessions closed");adminAudit=Objects.requireNonNull(audit);}
public synchronized void attachDownedDefeatRewards(java.util.function.Function<DownedEpisode,CompletionStage<?>> settlement){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");downedDefeatRewards=Objects.requireNonNull(settlement);}
public synchronized List<DownedEpisode.Reward> finalRewards(DownedEpisode episode){return List.copyOf(downedRewardAllocation.apply(Objects.requireNonNull(episode)));}
@@ -920,8 +926,142 @@ public final class EquipmentSessions implements AutoCloseable {
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())){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);});}
/** Replay only the saved entry return after native custody proof; ordinary native refusal retains the existing Tail fallback. */
private boolean returnRecoveredDeath(Attempt attempt, DownedEpisode episode) {
var world = resolveWorld(attempt.player, episode.entryWorld());
if (world == null) {
retainRecovery(attempt, "return_world_unavailable");
return false;
}
attempt.entryLocation = location(world, episode.entryX(), episode.entryY(), episode.entryZ(),
episode.entryYaw(), episode.entryPitch());
attempt.defeatReturnTeleport = true;
try {
boolean returned = attempt.player.teleport(attempt.entryLocation.clone());
if (downedEvents != null) downedEvents.returnAttempted(episode, returned ? "returned" : "refused");
if (!returned) notice(attempt.owner, "DEFEAT_RETURN_FAILED",
"Return to the session entry location was refused; you remain here.");
return true;
} catch (RuntimeException failure) {
attempt.nativeUncertain = true;
if (downedEvents != null) downedEvents.returnAttempted(episode, "uncertain");
conversionUncertain(attempt, "Recovered final-death return was uncertain; retained native custody");
diagnostic(attempt, failure);
return false;
} finally {
attempt.defeatReturnTeleport = false;
if (!attempt.deliveryInvalidated && owned.get(attempt.owner) == attempt && attempt.player.isOnline())
attempt.deathView = attempt.player.getOpenInventory();
captureRecoveryLocations(attempt);
}
}
/** Historical offline finalization has no pending receipt: the completed exit and native state must agree. */
private void reconcileCompletedDeath(Attempt attempt, EquipmentSessionStore.State state, DownedEpisode episode) {
var prior = attempt.recoveryOwner;
var exit = state == null ? null : state.lastExit();
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (state == null || state.pending() != null || exit == null
|| !exit.sessionId().equals(episode.session()) || !exit.characterId().equals(episode.character())
|| marker == null || !marker.matches(episode.session(), episode.character())
|| marker.phase() != EquipmentSessionMarker.Phase.RESTORED
|| resolveWorld(attempt.player, episode.entryWorld()) == null
|| hasRemnants(attempt.player) || prior != null && (prior.nativeUncertain
|| !prior.defeated || prior.receiptUncertain || !prior.gearAcknowledged
|| !deathProof(prior, episode))) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"Completed exit, exact death and native restored custody could not be proved; no item was changed.");
return;
}
if (transitioning.putIfAbsent(attempt.owner, attempt) != null) return;
attempt.completedDeathRead = true;
// Character work may outlive this Player. A new arrival is never allowed to publish
// through a stale callback, and the original owner's outstanding claim is retained.
persist(() -> characters.find(episode.character()).thenCompose(found -> {
if (found.isPresent() && deadFor(found.orElseThrow(), episode))
return finalConsequences(episode).thenApply(ignored -> found);
if (found.isPresent() && found.orElseThrow().dead())
return CompletableFuture.completedStage(Optional.empty());
return recordOfflineFinalDeath(episode);
}), (dead, failure) -> {
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
try {
if (failure != null) { diagnostic(attempt, failure); return; }
var currentDeath = unresolvedFinalDeath(attempt.owner);
if (dead == null || dead.isEmpty() || !deadFor(dead.orElseThrow(), episode)
|| closed || !attempt.player.isOnline() || currentDeath == null
|| !currentDeath.id().equals(episode.id())
|| transitioning.get(attempt.owner) != attempt
|| owned.get(attempt.owner) != prior) return;
if (!unchangedRecovery(attempt) || resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
var liveMarker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (liveMarker == null || !liveMarker.matches(episode.session(), episode.character())
|| liveMarker.phase() != EquipmentSessionMarker.Phase.RESTORED
|| hasRemnants(attempt.player)) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"Completed exit or exact saved sheet changed before Tail delivery; no item was changed.");
return;
}
if (prior != null && prior.player == attempt.player) {
retryTail(attempt.player, prior);
return;
}
var current = attempt.player.getInventory().getItemInOffHand();
var existing = tails.identify(current).orElse(null);
if (existing != null) {
if (existing.characterId().equals(episode.character()) && existing.deathId().equals(episode.id()))
publishRecoveredDowned(episode);
return;
}
if (!sheets.authorizes(current, dead.orElseThrow())) {
notice(attempt.owner, "DOWNED_RECOVERY_REQUIRED",
"The current sheet does not match the saved death; no item was changed.");
return;
}
attempt.defeated = true;
attempt.finalDowned = episode;
attempt.deathResolved = true;
attempt.deathRecord = dead.orElseThrow();
attempt.gearAcknowledged = true;
attempt.partyDefeatAcknowledged = true;
attempt.session = episode.session();
attempt.character = episode.character();
attempt.claim = prior == null ? null : prior.claim;
owned.put(attempt.owner, attempt);
if (prior != null) prior.deliveryInvalidated = true;
attempt.deathReference = copy(current);
attempt.deathNativeReference = nativeIdentity(current);
attempt.deathView = attempt.player.getOpenInventory();
if (returnRecoveredDeath(attempt, episode)) deliverTail(attempt, dead.orElseThrow());
} finally {
transitioning.remove(attempt.owner, attempt);
finishDrain();
}
}
});
} catch (RuntimeException rejected) {
transitioning.remove(attempt.owner, attempt);
diagnostic(attempt, rejected);
finishDrain();
}
});
}
private void publishRecoveredDowned(DownedEpisode episode){
var current = unresolvedFinalDeath(episode.player());
if(closed || current == null || !current.id().equals(episode.id()))return;
if(downedEvents!=null)downedEvents.outcomePublished(episode);
downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((published,failure)->{
synchronized(EquipmentSessions.this){
if(failure!=null)diagnostic(new Failure(episode.player(),episode.session(),failure));
else if(!closed&&downedEvents!=null)downedEvents.outcomePublished(published);
}
});
}
/** No automatic delivery after quit/respawn, including a reconnect of the same Player ID. */
public synchronized void invalidateContext(UUID owner) {
@@ -948,7 +1088,10 @@ public final class EquipmentSessions implements AutoCloseable {
}
private void queueTail(Attempt attempt) {
if (closed || attempt.tailCallbackQueued || attempt.bookAttempted || attempt.bookDelivered
// Persistence callbacks may enqueue immutable authority; native online/view/item checks
// belong to deliverTail on the owner thread, never the receipt/death worker.
if (closed || owned.get(attempt.owner) != attempt
|| attempt.tailCallbackQueued || attempt.bookAttempted || attempt.bookDelivered
|| attempt.deliveryInvalidated || !attempt.deathResolved || !attempt.partyDefeatAcknowledged
|| !attempt.gearAcknowledged || attempt.deathRecord == null) return;
attempt.tailCallbackQueued = true;
@@ -985,8 +1128,14 @@ public final class EquipmentSessions implements AutoCloseable {
}
private void deliverTail(Attempt attempt, CharacterRecord dead) {
if (attempt.bookAttempted || attempt.bookDelivered) return;
if (owned.get(attempt.owner) != attempt || attempt.bookAttempted || attempt.bookDelivered) return;
try {
if (attempt.finalDowned != null && (!attempt.deathResolved || !attempt.partyDefeatAcknowledged
|| !attempt.gearAcknowledged || !deadFor(dead, attempt.finalDowned)
|| !deathProof(attempt, unresolvedFinalDeath(attempt.owner)))) {
conversionUncertain(attempt, "Exact final-death prerequisites were not acknowledged before Tail delivery");
return;
}
if (!tailContext(attempt) || !tailCustody(attempt)) {
conversionUncertain(attempt, "Tail destination/context is stale or equipment restoration is unresolved"); return;
}
@@ -1108,10 +1257,17 @@ public final class EquipmentSessions implements AutoCloseable {
return EquipmentStorage.RestoreResult.INVALID_BOX;
}
boolean vitalsRestored = restoreVitals(attempt);
attempt.restorationRefused = result != EquipmentStorage.RestoreResult.RESTORED;
if (result == EquipmentStorage.RestoreResult.RESTORED && (!modeRestored || !vitalsRestored || !attempt.healthAcknowledged)) {
attempt.gearRestoredForModeRecovery = true;
}
captureRecoveryLocations(attempt);
if (result == EquipmentStorage.RestoreResult.RESTORED && attempt.defeated && attempt.deathReference == null) {
var retained = attempt.player.getInventory().getItemInOffHand();
attempt.deathReference = copy(retained);
attempt.deathNativeReference = nativeIdentity(retained);
attempt.deathView = attempt.player.getOpenInventory();
}
persistExit(attempt, result == EquipmentStorage.RestoreResult.RESTORED && modeRestored && vitalsRestored);
if (result != EquipmentStorage.RestoreResult.RESTORED) {
if (equipmentEvents != null) {
@@ -1231,16 +1387,39 @@ public final class EquipmentSessions implements AutoCloseable {
attempt.recoveryCurrentLocation = sessionRecoveryEvents.captureLocation(attempt.player.getLocation());
}
private void adminRecoveryResult(Attempt attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome outcome,
String reason) {
if (adminAudit == null || attempt.adminRecoveryAction == null) return;
var facts = new java.util.LinkedHashMap<String, Object>();
if (attempt.sessionRecoveryAction != null) facts.put("domain_operation_id", attempt.sessionRecoveryAction.id());
if (attempt.character != null) facts.put("subject_id", attempt.character);
adminAudit.result(attempt.adminRecoveryAction, outcome, reason, facts);
}
private void sessionReconciled(Attempt attempt, String phase, String outcome, String quality,
String reason, java.math.BigInteger revision) {
if (sessionRecoveryEvents == null || attempt.sessionRecoveryAction == null || attempt.sessionRecoveryResolved) return;
if (attempt.sessionRecoveryResolved
|| (sessionRecoveryEvents == null || attempt.sessionRecoveryAction == null)
&& attempt.adminRecoveryAction == null) return;
attempt.sessionRecoveryResolved = true;
try {
sessionRecoveryEvents.reconciled(attempt.sessionRecoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, phase, outcome, quality, reason, attempt.recoveryReceiptRevision,
revision, attempt.recoveryAction == null ? null : attempt.recoveryAction.id(),
attempt.recoveryOriginalLocation, attempt.recoveryCurrentLocation);
if (sessionRecoveryEvents != null && attempt.sessionRecoveryAction != null)
sessionRecoveryEvents.reconciled(attempt.sessionRecoveryAction, attempt.session, attempt.character,
attempt.recoveryPriorPhase, phase, outcome, quality, reason, attempt.recoveryReceiptRevision,
revision, attempt.recoveryAction == null ? null : attempt.recoveryAction.id(),
attempt.recoveryOriginalLocation, attempt.recoveryCurrentLocation);
} catch (RuntimeException failure) { diagnostic(attempt, failure); }
adminRecoveryResult(attempt, switch (outcome) {
case "restored" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.COMPLETED;
case "failed" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED;
case "retained" -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED;
default -> games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN;
}, switch (outcome) {
case "restored" -> "acknowledged";
case "failed" -> "operation_failed";
case "retained" -> "owner_refused";
default -> "operation_uncertain";
});
}
private void nutritionRetained(Attempt attempt, String reason) {
@@ -1290,61 +1469,93 @@ public final class EquipmentSessions implements AutoCloseable {
persist(() -> complete
? receipts.completeExit(attempt.owner, attempt.session, attempt.exitDelay)
: receipts.recordExit(attempt.owner, attempt.session, attempt.exitDelay), (state, failure) -> {
attempt.saving = false;
if (failure != null) {
nutritionRetained(attempt, "receipt_save_failed");
sessionReconciled(attempt,
attempt.nativeRestored ? "restored" : "pending",
attempt.nativeRestored ? "ambiguous" : "failed",
attempt.nativeRestored ? "native_restored_receipt_pending" : "receipt_unavailable",
"receipt_save_failed", attempt.recoveryReceiptRevision);
diagnostic(attempt, failure);
if (attempt.defeated) conversionUncertain(attempt,
"Equipment restoration persistence failed before Tail conversion");
} else if (complete) {
attempt.gearAcknowledged = true;
if (!attempt.restoreEventWritten && equipmentEvents != null && attempt.restoreEvent != null) {
attempt.restoreEventWritten = true;
equipmentEvents.restored(attempt.restoreEvent, state.revision());
}
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.restoreAction, "accepted", "receipt_completed");
if (attempt.recoveryAction != null && !attempt.recoveryResolved) {
attempt.recoveryResolved = true;
equipmentEvents.resolved(attempt.recoveryAction, "accepted", "receipt_completed");
equipmentEvents.recovery(attempt.recoveryAction,
attempt.session, attempt.character, attempt.recoveryPriorPhase, "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"restored", "receipt_completed", state.revision());
if (attempt.finalDowned == null) {
exitAcknowledged(attempt, complete, state, failure);
return;
}
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
exitAcknowledged(attempt, complete, state, failure);
}
}
sessionReconciled(attempt, "restored", "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"receipt_completed", state.revision());
if (!attempt.switchEventWritten && switchEvents != null) {
attempt.switchEventWritten = true;
switchEvents.started(attempt.switchExit, state);
}
if (!attempt.nutritionRestoreWritten && nutritionEvents != null
&& attempt.nutritionAfterRestore != null) {
attempt.nutritionRestoreWritten = true;
nutritionEvents.restored(attempt.nutritionBeforeRestore, attempt.nutritionAfterRestore,
attempt.ordinaryVitals, state.revision());
}
if (!attempt.defeated && !attempt.exitEventWritten && attempt.exitEvent != null && sessionEvents != null) {
attempt.exitEventWritten = true;
sessionEvents.exited(attempt.session,attempt.exitEvent);
}
if (attempt.defeated) queueTail(attempt);
release(attempt);
} else {
nutritionRetained(attempt, !attempt.healthAcknowledged ? "health_unverified" : "receipt_incomplete");
if (attempt.defeated) conversionUncertain(attempt,
"Equipment restoration was not acknowledged; Tail conversion remains unsafe");
});
} catch (RuntimeException rejected) {
attempt.saving = false;
attempt.receiptUncertain = true;
conversionUncertain(attempt, "Native death acknowledgement scheduling was refused; retain completed receipt and custody");
diagnostic(attempt, rejected);
}
});
}
/** Final-death acknowledgment is handed back to the native owner before item/view validation. */
private void exitAcknowledged(Attempt attempt, boolean complete, EquipmentSessionStore.State state, Throwable failure) {
attempt.saving = false;
if (failure != null) {
if (attempt.defeated) attempt.receiptUncertain = true;
nutritionRetained(attempt, "receipt_save_failed");
sessionReconciled(attempt,
attempt.nativeRestored ? "restored" : "pending",
attempt.nativeRestored ? "ambiguous" : "failed",
attempt.nativeRestored ? "native_restored_receipt_pending" : "receipt_unavailable",
"receipt_save_failed", attempt.recoveryReceiptRevision);
diagnostic(attempt, failure);
if (attempt.defeated) conversionUncertain(attempt,
"Equipment restoration persistence failed before Tail conversion");
} else if (complete && attempt.finalDowned != null && (closed || owned.get(attempt.owner) != attempt
|| !attempt.player.isOnline() || state.pending() != null || state.lastExit() == null
|| !state.lastExit().sessionId().equals(attempt.session)
|| !state.lastExit().characterId().equals(attempt.character)
|| attempt.deathResolved && !deathProof(attempt, unresolvedFinalDeath(attempt.owner))
|| !tailContext(attempt) || !tailCustody(attempt))) {
conversionUncertain(attempt, "Native death custody changed before receipt acknowledgement; completion is not Tail authority");
} else if (complete) {
attempt.gearAcknowledged = true;
if (!attempt.restoreEventWritten && equipmentEvents != null && attempt.restoreEvent != null) {
attempt.restoreEventWritten = true;
equipmentEvents.restored(attempt.restoreEvent, state.revision());
}
if (equipmentEvents != null) {
equipmentEvents.resolved(attempt.restoreAction, "accepted", "receipt_completed");
if (attempt.recoveryAction != null && !attempt.recoveryResolved) {
attempt.recoveryResolved = true;
equipmentEvents.resolved(attempt.recoveryAction, "accepted", "receipt_completed");
equipmentEvents.recovery(attempt.recoveryAction,
attempt.session, attempt.character, attempt.recoveryPriorPhase, "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"restored", "receipt_completed", state.revision());
}
}
sessionReconciled(attempt, "restored", "restored",
attempt.restoreEvent == null ? "receipt_and_marker_only" : "verified_box_and_marker",
"receipt_completed", state.revision());
if (!attempt.switchEventWritten && switchEvents != null) {
attempt.switchEventWritten = true;
switchEvents.started(attempt.switchExit, state);
}
if (!attempt.nutritionRestoreWritten && nutritionEvents != null
&& attempt.nutritionAfterRestore != null) {
attempt.nutritionRestoreWritten = true;
nutritionEvents.restored(attempt.nutritionBeforeRestore, attempt.nutritionAfterRestore,
attempt.ordinaryVitals, state.revision());
}
if (!attempt.defeated && !attempt.exitEventWritten && attempt.exitEvent != null && sessionEvents != null) {
attempt.exitEventWritten = true;
sessionEvents.exited(attempt.session,attempt.exitEvent);
}
if (attempt.defeated) queueTail(attempt);
release(attempt);
} else {
nutritionRetained(attempt, !attempt.healthAcknowledged ? "health_unverified" : "receipt_incomplete");
if (attempt.defeated) {
if (attempt.restorationRefused)
conversionNotStarted(attempt, "Equipment restoration was refused; receipt and Tail custody retained");
else conversionUncertain(attempt,
"Equipment restoration was not acknowledged; Tail conversion remains unsafe");
}
}
}
/** A synchronous exit request is not proof of an acknowledged character/receipt restoration. */
public record DisableSummary(int entryRefused, int exitRequested, int nativeRestoredPendingReceipt,
int exitFailed, int exitPending) { }
@@ -1373,7 +1584,11 @@ public final class EquipmentSessions implements AutoCloseable {
public synchronized void cancelEntry(UUID player) {
var attempt = pending.remove(player);
if (attempt != null) abandon(attempt);
if (attempt != null) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
abandon(attempt);
}
}
private void abandon(Attempt attempt) {
@@ -1417,6 +1632,8 @@ public final class EquipmentSessions implements AutoCloseable {
notice(attempt.owner, code, message);
}
private void fail(Attempt attempt, Throwable failure) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
if (attempt.effectsStarted && owned.get(attempt.owner) == attempt) attempt.nativeUncertain = true;
pending.remove(attempt.owner, attempt);
active.remove(attempt.owner, attempt);
@@ -1444,7 +1661,11 @@ public final class EquipmentSessions implements AutoCloseable {
private synchronized void schedule(Attempt attempt, Runnable callback) {
// close already invalidates pending work and owns its never-packed cleanup. Accepted
// reads may still finish, but must not require another task on a disabled scheduler.
if (closed) return;
if (closed) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN,
"operation_uncertain");
return;
}
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
@@ -1463,40 +1684,56 @@ public final class EquipmentSessions implements AutoCloseable {
}
/** Explicit proof-based reconciliation; never infer restoration from an absent box. */
public synchronized void recover(Player player) { recover(player, false, null); }
public synchronized void recover(Player player) { recover(player, false, null, null); }
public synchronized void recover(Player player, games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action) {
recover(player, false, action);
recover(player, false, action, null);
}
/** Join reconciliation: recover a pending receipt, otherwise request normal entry. */
public synchronized void arrive(Player player) {
var directory=downedDirectory;
if(directory!=null){var death=directory.all().stream().filter(value->value.player().equals(player.getUniqueId())&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.FINAL_DEATH&&!value.published()).findFirst().orElse(null);if(death!=null){reconcileOfflineFinalDeath(player,death);return;}}
recover(player,true,null);
/** The command's captured action is carried across receipt I/O, not rediscovered from a callback thread. */
public synchronized void recover(Player player, games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action,
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminAction) {
recover(player, false, action, adminAction);
}
/** Read the receipt before considering any historical no-pending-receipt Tail delivery. */
public synchronized void arrive(Player player) { recover(player, true, null, null); }
private void recover(Player player, boolean arrival,
games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action) {
games.dmg.fantasystick.events.SessionRecoveryEventBridge.Action action,
games.dmg.fantasystick.events.AdminActionEventBridge.Action adminAction) {
UUID owner = player.getUniqueId();
invalidateCursor(owner);
if (closed || !player.isOnline()) return;
var refused = new Attempt(player, owner, null);
refused.sessionRecoveryAction = action;
refused.adminRecoveryAction = adminAction;
if (closed || !player.isOnline()) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
return;
}
var previous = owned.get(owner);
if (previous != null && previous.defeated && (arrival || previous.gearAcknowledged
|| previous.bookDelivered || previous.player != player)) {
if (previous != null && previous.defeated && (previous.bookAttempted || previous.bookDelivered
|| !arrival && previous.gearAcknowledged)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
notice(owner, "DEFEAT_PENDING", "Death or Tail conversion is pending/uncertain; retained state requires inspection, not automatic replay."); return;
}
if (previous != null && previous.nativeUncertain) {
notice(owner, "NATIVE_UNCERTAIN", "A native equipment write had an uncertain outcome; automatic restoration is unsafe. Retain items for inspection."); return;
if (previous != null && (previous.nativeUncertain || previous.receiptUncertain)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain");
notice(owner, "NATIVE_UNCERTAIN", "An equipment or receipt write had an uncertain outcome; automatic restoration is unsafe. Retain items for inspection."); return;
}
if (transitioning.containsKey(owner) || active.containsKey(owner)
|| previous != null && (previous.saving || previous.cleaning)) {
adminRecoveryResult(refused, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
notice(owner, "BUSY", "A session transition is still pending; recovery did not change items."); return;
}
cancelEntry(owner);
var attempt = new Attempt(player, owner, null);
attempt.recoveryOwner = previous;
attempt.snapshot = snapshot(player);
attempt.cursor = copy(player.getItemOnCursor());
attempt.entryMarker = EquipmentSessionMarker.read(player).orElse(null);
attempt.sessionRecoveryAction = action;
attempt.adminRecoveryAction = adminAction;
// A recovered receipt has no process-local never-packed proof.
attempt.effectsStarted = true;
attempt.arrival = arrival;
@@ -1505,11 +1742,149 @@ public final class EquipmentSessions implements AutoCloseable {
schedule(attempt, () -> recovered(attempt, state, failure)));
}
private DownedEpisode unresolvedFinalDeath(UUID owner) {
return downedDirectory == null ? null : downedDirectory.all().stream()
.filter(value -> value.player().equals(owner) && value.phase() == DownedEpisode.Phase.RESOLVED
&& value.outcome() == DownedEpisode.Outcome.FINAL_DEATH && !value.published())
.findFirst().orElse(null);
}
private static boolean deadFor(CharacterRecord record, DownedEpisode episode) {
return record != null && episode != null && record.id().equals(episode.character())
&& record.dead() && episode.id().equals(record.deathId())
&& episode.resolvedAt().equals(record.diedAt());
}
private static boolean deathProof(Attempt previous, DownedEpisode episode) {
return episode != null && previous.finalDowned != null && previous.finalDowned.id().equals(episode.id())
&& previous.owner.equals(episode.player()) && previous.session.equals(episode.session())
&& previous.character.equals(episode.character()) && previous.deathResolved
&& deadFor(previous.deathRecord, episode);
}
private void retainRecovery(Attempt attempt, String reason) {
if (equipmentEvents != null) equipmentEvents.resolved(attempt.recoveryAction, "retained", reason);
sessionReconciled(attempt, "pending", "retained", "receipt_and_marker_only", reason,
attempt.recoveryReceiptRevision);
notice(attempt.owner, "DEFEAT_INSPECTION_REQUIRED", "Death or equipment custody is unproved ("
+ reason + "); the original receipt and native items were retained.");
}
private boolean unchangedRecovery(Attempt attempt) {
return Arrays.equals(attempt.snapshot, snapshot(attempt.player))
&& Objects.equals(attempt.cursor, copy(attempt.player.getItemOnCursor()))
&& Objects.equals(attempt.entryMarker, EquipmentSessionMarker.read(attempt.player).orElse(null));
}
private boolean packedDeathCustody(Attempt attempt, DownedEpisode episode) {
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
return attempt.session.equals(episode.session()) && attempt.character.equals(episode.character())
&& unchangedRecovery(attempt) && marker != null
&& marker.matches(attempt.session, attempt.character)
&& marker.phase() == EquipmentSessionMarker.Phase.PACKED
&& equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).isPresent();
}
/** A cold coordinator must continue the same death through restoration, receipt and Tail, on its first arrival. */
private void reconcilePendingDeath(Attempt attempt, DownedEpisode episode) {
if (!packedDeathCustody(attempt, episode) || resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "native_custody_unverified");
return;
}
if (transitioning.putIfAbsent(attempt.owner, attempt) != null) return;
attempt.completedDeathRead = true;
attempt.defeated = true;
attempt.finalDowned = episode;
attempt.exitReason = "defeat";
owned.put(attempt.owner, attempt);
persist(() -> characters.find(episode.character()).thenCompose(found -> {
if (found.isPresent() && deadFor(found.orElseThrow(), episode))
return finalConsequences(episode).thenApply(ignored -> found);
if (found.isPresent() && found.orElseThrow().dead())
return CompletableFuture.completedStage(Optional.empty());
return recordOfflineFinalDeath(episode);
}), (dead, failure) -> {
try {
nextTick.accept(() -> {
synchronized (EquipmentSessions.this) {
try {
if (failure != null) {
diagnostic(attempt, failure);
conversionUncertain(attempt, "Pending death persistence/consequences were not acknowledged");
return;
}
var currentDeath = unresolvedFinalDeath(attempt.owner);
if (closed || !attempt.player.isOnline() || owned.get(attempt.owner) != attempt
|| transitioning.get(attempt.owner) != attempt || currentDeath == null
|| !currentDeath.id().equals(episode.id())) return;
if (dead == null || dead.isEmpty() || !deadFor(dead.orElseThrow(), episode)
|| !packedDeathCustody(attempt, episode)
|| resolveWorld(attempt.player, episode.entryWorld()) == null) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
attempt.record = dead.orElseThrow();
attempt.deathRecord = attempt.record;
attempt.deathResolved = true;
attempt.partyDefeatAcknowledged = true; // Actual consequence future succeeded.
attempt.recoveryPriorPhase = "packed";
if (restoreExit(attempt) == EquipmentStorage.RestoreResult.RESTORED)
returnRecoveredDeath(attempt, episode);
} finally {
transitioning.remove(attempt.owner, attempt);
finishDrain();
}
}
});
} catch (RuntimeException rejected) {
transitioning.remove(attempt.owner, attempt);
conversionUncertain(attempt, "Pending death native scheduling was refused");
diagnostic(attempt, rejected);
finishDrain();
}
});
}
/** Transfer the original claim and death authority only after current-Player proof, not on UUID alone. */
private Attempt rebindDeath(Attempt previous, Attempt rebound) {
rebound.claim = previous.claim;
rebound.record = previous.record;
rebound.deathRecord = previous.deathRecord;
rebound.finalDowned = previous.finalDowned;
rebound.deathResolved = previous.deathResolved;
rebound.partyDefeatAcknowledged = previous.partyDefeatAcknowledged;
rebound.defeated = true;
rebound.exitReason = previous.exitReason;
rebound.entryLocation = previous.entryLocation;
rebound.exitDelay = previous.exitDelay;
rebound.healthAcknowledged = previous.healthAcknowledged;
rebound.switchExit = previous.switchExit;
rebound.switchEventWritten = previous.switchEventWritten;
rebound.nutritionRestoreWritten = previous.nutritionRestoreWritten;
rebound.nutritionRetainedWritten = previous.nutritionRetainedWritten;
rebound.nutritionBeforeRestore = previous.nutritionBeforeRestore;
rebound.nutritionAfterRestore = previous.nutritionAfterRestore;
rebound.gearRestoredForModeRecovery = false; // Never inherit same-Player native proof.
rebound.recoveryPriorPhase = EquipmentSessionMarker.read(rebound.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
previous.deliveryInvalidated = true;
owned.put(rebound.owner, rebound);
return rebound;
}
private synchronized void recovered(Attempt attempt, Optional<EquipmentSessionStore.State> state, Throwable failure) {
if (!current(attempt)) return;
if (!current(attempt)) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain");
return;
}
pending.remove(attempt.owner, attempt);
if (!attempt.player.isOnline()) return;
if (!attempt.player.isOnline()) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "owner_refused");
return;
}
if (owned.get(attempt.owner) != attempt.recoveryOwner) {
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "stale");
notice(attempt.owner, "STALE_RECOVERY", "Session ownership changed after the recovery read; no old receipt was replayed.");
return;
}
@@ -1521,12 +1896,19 @@ public final class EquipmentSessions implements AutoCloseable {
"failed", "receipt_unreadable", "receipt_read_failed", null, null, null, null,
sessionRecoveryEvents.captureLocation(attempt.player.getLocation()));
}
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.FAILED, "operation_failed");
diagnostic(attempt, failure); return;
}
var receipt = state.map(EquipmentSessionStore.State::pending).orElse(null);
if (receipt == null) {
if (attempt.arrival) {
var episode=downedDirectory==null?null:downedDirectory.all().stream().filter(value->value.player().equals(attempt.owner)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
var death = unresolvedFinalDeath(attempt.owner);
if (death != null) {
reconcileCompletedDeath(attempt, state.orElse(null), death);
return;
}
var arrivingOwner = attempt.owner;
var episode=downedDirectory==null?null:downedDirectory.all().stream().filter(value->value.player().equals(arrivingOwner)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player,episode);
else if (EquipmentSessionMarker.present(attempt.player) || hasRemnants(attempt.player)) {
notice(attempt.owner, "NATIVE_RECOVERY_REQUIRED", "Native equipment remnants have no pending receipt; items were retained for inspection.");
@@ -1542,6 +1924,7 @@ public final class EquipmentSessions implements AutoCloseable {
"receipt_missing", "no_receipt", null, null, null, null,
sessionRecoveryEvents.captureLocation(attempt.player.getLocation()));
}
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "not_found");
notice(attempt.owner, "NO_RECEIPT", "No saved equipment receipt is available; items were left unchanged."); return;
}
attempt.character = receipt.characterId();
@@ -1558,21 +1941,52 @@ public final class EquipmentSessions implements AutoCloseable {
attempt.healthAcknowledged = !attempt.vitalsStarted;
attempt.modeStarted = attempt.previousGameMode != null;
var previous = owned.get(attempt.owner);
var savedDeath = unresolvedFinalDeath(attempt.owner);
if (savedDeath != null && (!attempt.session.equals(savedDeath.session())
|| !attempt.character.equals(savedDeath.character()) || !unchangedRecovery(attempt))) {
retainRecovery(attempt, "death_or_native_custody_changed");
return;
}
if (previous == null && attempt.arrival && savedDeath != null) {
reconcilePendingDeath(attempt, savedDeath);
return;
}
if (previous != null && !attempt.session.equals(previous.session)) {
if (equipmentEvents != null) equipmentEvents.resolved(attempt.recoveryAction, "refused", "session_mismatch");
adminRecoveryResult(attempt, games.dmg.fantasystick.events.AdminActionEventBridge.Outcome.REFUSED, "stale");
notice(attempt.owner, "SESSION_MISMATCH", "Saved and process-local sessions disagree; items were left unchanged."); return;
}
if (previous != null && (previous.defeated || previous.vitalsStarted)) {
// Explicit same-lifetime equipment recovery still uses matching receipt/PACKED
// proof. Keep the original death authority and its pending worker completion;
// do not replace it with a recovery Attempt that could release its claim early.
previous.deliveryInvalidated = true;
previous.recoveryAction = attempt.recoveryAction;
previous.sessionRecoveryAction = attempt.sessionRecoveryAction;
previous.recoveryReceiptRevision = attempt.recoveryReceiptRevision;
previous.recoveryPriorPhase = EquipmentSessionMarker.read(attempt.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
restoreExit(previous);
if (previous.finalDowned != null && !deathProof(previous, unresolvedFinalDeath(attempt.owner))) {
retainRecovery(attempt, "death_unverified");
return;
}
if (previous.player != attempt.player) {
// Never use a same-UUID obsolete Player's inventory or its native identity as
// custody proof. Rebind only after inspecting the current Player's PACKED box.
var marker = EquipmentSessionMarker.read(attempt.player).orElse(null);
if (!previous.defeated || previous.finalDowned == null || previous.saving || !previous.deathResolved
|| !previous.partyDefeatAcknowledged
|| marker == null || !marker.matches(attempt.session, attempt.character)
|| marker.phase() != EquipmentSessionMarker.Phase.PACKED
|| equipment.snapshot(attempt.player.getInventory(), attempt.owner, attempt.session,
attempt.player.getItemOnCursor()).isEmpty()) {
retainRecovery(attempt, "native_custody_unverified");
return;
}
attempt = rebindDeath(previous, attempt);
} else {
// A refused same-Player restoration is retryable only while its first native
// write returned a definite refusal; an exception is never automatically replayed.
previous.recoveryAction = attempt.recoveryAction;
previous.sessionRecoveryAction = attempt.sessionRecoveryAction;
previous.adminRecoveryAction = attempt.adminRecoveryAction;
previous.recoveryReceiptRevision = attempt.recoveryReceiptRevision;
previous.recoveryPriorPhase = EquipmentSessionMarker.read(attempt.player)
.map(token -> token.phase().name().toLowerCase(java.util.Locale.ROOT)).orElse("unavailable");
attempt = previous;
}
restoreExit(attempt);
return;
}
if (previous != null) {
@@ -1633,7 +2047,11 @@ public final class EquipmentSessions implements AutoCloseable {
if (closed) return;
closed = true;
try {
for (var attempt : transitioning.values()) {
for (var attempt : java.util.List.copyOf(transitioning.values())) {
if (attempt.completedDeathRead) {
transitioning.remove(attempt.owner, attempt);
continue; // No native mutation has begun; stale read callbacks must not publish.
}
attempt.exitRequested = true;
withdrawPresentation(attempt);
}