feat(frost-shard): audit owned arrow and slow outcomes
Release / release (push) Successful in 17m59s

This commit is contained in:
dmg committed 2026-09-25 21:52:30 -04:00
1 parent db4c3b2842
commit f6d95ca338
8 files changed
+531 -34

No files matched your search

@@ -741,6 +741,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
particlesCommand.attachEvents(preferenceEvents);
feedbackCommand.attachEvents(preferenceEvents);
eventCapture.excludeOwnedDamage(fireball::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(frostShard::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(greatSword::ownsAcceptedDamage);
eventCapture.excludeOwnedDamage(guardianBond::ownsAcceptedRedirect);
eventCapture.excludeOwnedDamage(frostNova::ownsAcceptedDamage);
@@ -757,6 +758,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
abilityEngine.attachCastEvents(new games.dmg.fantasystick.events.AbilityCastEventBridge(eventLog::emit, Clock.systemUTC()));
abilityEngine.enableCastEventsFor("fireball");
abilityEngine.enableCastEventsFor("great_sword");
abilityEngine.enableCastEventsFor("frost_shard");
abilityEngine.enableCastEventsFor("mending_light");
abilityEngine.enableCastEventsFor("purify");
abilityEngine.enableCastEventsFor("guardian_bond");
@@ -458,9 +458,13 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
castEvents.boosted(audit, attacking, attacker, target, base, bonus, finalDamage, percent);
}
@Override public void effectEnded(UUID application, String reason) {
Objects.requireNonNull(application); Objects.requireNonNull(reason);
effectEnded(application, reason, Map.of());
}
@Override public void effectEnded(UUID application, String reason, Map<String, Object> evidence) {
Objects.requireNonNull(application); Objects.requireNonNull(reason); Objects.requireNonNull(evidence);
var effectId = observedEffects.remove(application);
if (effectId != null && castEvents != null) castEvents.effectEnded(audit, application, effectId, reason);
if (effectId != null && castEvents != null)
castEvents.effectEnded(audit, application, effectId, reason, evidence);
}
@Override public void resolve(String result) { resolve(result, Map.of()); }
@Override public void resolve(String result, Map<String, Object> evidence) {
@@ -46,6 +46,10 @@ public interface AbilityExecution extends AutoCloseable {
double base, double bonus, double finalDamage, java.math.BigDecimal percent);
/** End an owned observed effect once; ordinary close ends any remaining observed effects. */
void effectEnded(UUID applicationId, String reason);
/** End an observed effect with actual native cleanup/restoration evidence. */
default void effectEnded(UUID applicationId, String reason, Map<String, Object> evidence) {
effectEnded(applicationId, reason);
}
/** An owner may specify a truthful terminal outcome before finishing. */
void resolve(String outcome);
void resolve(String outcome, Map<String, Object> evidence);
@@ -6,6 +6,7 @@ import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -58,7 +59,9 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
final BigInteger intelligence;
final Settings settings;
LivingEntity target;
double requested;
boolean accepted;
boolean nativeCancelled;
boolean finished;
State(Arrow projectile, AbilityExecution execution, Location origin, BigInteger intelligence, Settings settings) {
this.projectile = projectile; this.execution = execution; this.origin = origin;
@@ -74,13 +77,33 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
private final LivingEntity target;
private final PotionEffect previous;
private final PotionEffect applied;
private final AbilityExecution execution;
private final long started = System.nanoTime();
private UUID application;
private String endReason = "interrupted";
private boolean owned;
private boolean closed;
SlowLease(LivingEntity target, PotionEffect applied) {
SlowLease(LivingEntity target, PotionEffect applied, AbilityExecution execution) {
this.target = target; this.previous = target.getPotionEffect(PotionEffectType.SLOWNESS); this.applied = applied;
this.execution = execution;
}
boolean apply() { owned = target.addPotionEffect(applied); return owned; }
boolean apply() {
owned = target.addPotionEffect(applied);
if (owned) try {
var evidence = new LinkedHashMap<String, Object>();
evidence.put("amplifier", applied.getAmplifier());
evidence.put("duration_ticks", applied.getDuration());
evidence.put("deadline", java.time.Instant.now().plusMillis(applied.getDuration() * 50L).toString());
evidence.put("prior_layer", previous == null ? "none" : "replaced");
if (previous != null) {
evidence.put("prior_amplifier", previous.getAmplifier());
evidence.put("prior_duration_ticks", previous.getDuration());
}
application = execution.effectApplied("frost_shard_slowness", target, evidence);
} catch (RuntimeException ignored) { /* Native effect authority is independent of auditing. */ }
return owned;
}
void expire() { endReason = "expired"; close(); }
@Override public void close() {
if (closed) return;
closed = true;
@@ -88,13 +111,24 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
var current = target.getPotionEffect(PotionEffectType.SLOWNESS);
long elapsed = Math.max(0, (System.nanoTime() - started) / 50_000_000L);
int expected = (int) Math.max(0, (long) applied.getDuration() - elapsed);
if (current == null || current.getAmplifier() != applied.getAmplifier()
|| current.getDuration() > expected + 2) return;
if (current == null) {
end(endReason.equals("expired") ? "expired" : "native_layer_missing", "none"); return;
}
if (current.getAmplifier() != applied.getAmplifier()
|| current.getDuration() > expected + 2 || current.getDuration() < expected - 2) {
end("superseded", "preserved_newer"); return;
}
target.removePotionEffect(PotionEffectType.SLOWNESS);
String restored = "none";
if (previous != null) {
int remaining = (int) Math.max(0, (long) previous.getDuration() - elapsed);
if (remaining > 0) target.addPotionEffect(previous.withDuration(remaining));
if (remaining > 0)
restored = target.addPotionEffect(previous.withDuration(remaining)) ? "prior" : "refused";
}
end(endReason, restored);
}
private void end(String reason, String restored) {
if (application != null) execution.effectEnded(application, reason, Map.of("restored_layer", restored));
}
}
@@ -130,6 +164,18 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
AbilityDefinition.TargetPolicy.PROJECTILE_HOSTILE, this);
}
private static Settings captured(AbilityDefinition definition) {
var values = definition.parameters();
return new Settings(values.get("base-damage").toBigIntegerExact(), definition.cooldown(),
values.get("range").doubleValue(), duration(values.get("lifetime")),
values.get("projectile-speed").doubleValue(), values.get("slowness-amplifier").intValueExact(),
duration(values.get("slowness-duration")));
}
private static Duration duration(BigDecimal seconds) {
return Duration.ofNanos(seconds.movePointRight(9).toBigIntegerExact().longValueExact());
}
public static BigInteger damage(BigInteger intelligence) {
return damage(BigInteger.valueOf(4), intelligence);
}
@@ -146,7 +192,7 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
@Override public void activate(AbilityExecution execution) {
if (closed || !execution.stillCurrent()) return;
var current = settings;
var current = captured(execution.definition());
var player = execution.input().player();
Location origin = player.getEyeLocation().clone();
Vector direction = origin.getDirection();
@@ -161,12 +207,15 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
}
execution.own(state);
long rangeTicks = Math.max(1, (long) Math.ceil(current.range() / current.speedPerTick()));
execution.later(Duration.ofMillis(Math.multiplyExact(rangeTicks, 50)), () -> {
if (projectiles.containsKey(projectile.getUniqueId())) execution.finish();
});
execution.later(current.lifetime(), () -> {
if (projectiles.containsKey(projectile.getUniqueId())) execution.finish();
});
Runnable expire = () -> {
if (projectiles.containsKey(projectile.getUniqueId())) {
try { execution.resolve("expired", Map.of("projectile_id", projectile.getUniqueId().toString())); }
catch (RuntimeException ignored) { /* Audit capture cannot retain an expired Arrow. */ }
execution.finish();
}
};
execution.later(Duration.ofMillis(Math.multiplyExact(rangeTicks, 50)), expire);
execution.later(current.lifetime(), expire);
particles.world(Particle.SNOWFLAKE, origin, 8, 0.15, 0.15, 0.15, 0.01);
}
@@ -183,25 +232,38 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
if (state == null) return;
boolean retainExecution = false;
try {
if (closed || event.isCancelled() || !state.execution.stillCurrent()
boolean currentSession = !closed && state.execution.stillCurrent();
if (!currentSession || event.isCancelled()
|| !(event.getHitEntity() instanceof LivingEntity target) || !inRange(state, event.getEntity().getLocation())
|| state.execution.eligible(List.of(target), 1).isEmpty()) return;
|| state.execution.eligible(List.of(target), 1).isEmpty()) {
try { state.execution.resolve(!currentSession ? "interrupted" : event.isCancelled() ? "cancelled" : "miss",
Map.of("projectile_id", state.projectile.getUniqueId().toString())); }
catch (RuntimeException ignored) { /* Audit capture cannot retain an invalid hit. */ }
return;
}
var current = state.settings;
BigInteger amount = damage(current.baseDamage(), state.intelligence);
double nativeDamage = amount.bitLength() > 1023 ? Double.MAX_VALUE : amount.doubleValue();
var source = DamageSource.builder(DamageType.FREEZE).withCausingEntity(state.execution.input().player())
.withDirectEntity(state.projectile).withDamageLocation(state.projectile.getLocation()).build();
state.target = target; damaging = state;
state.target = target; state.requested = nativeDamage; damaging = state;
try { state.execution.damage(target, nativeDamage, source); }
finally { if (damaging == state) damaging = null; }
try { state.execution.resolve(state.accepted ? "hit" : state.nativeCancelled ? "cancelled" : "miss",
Map.of("projectile_id", state.projectile.getUniqueId().toString(),
"target_entity_id", target.getUniqueId().toString(),
"impact_location", locationData(state.projectile.getLocation()))); }
catch (RuntimeException ignored) { /* Capturing evidence cannot prevent native Slowness. */ }
if (state.accepted && state.execution.stillCurrent()) {
int ticks = Math.toIntExact(Math.max(1,
(current.slownessDuration().toNanos() + 49_999_999L) / 50_000_000L));
var lease = new SlowLease(target, new PotionEffect(PotionEffectType.SLOWNESS, ticks,
current.slownessAmplifier(), false, true, true));
current.slownessAmplifier(), false, true, true), state.execution);
if (lease.apply()) {
state.execution.own(lease);
state.execution.later(current.slownessDuration(), state.execution::finish);
state.execution.later(current.slownessDuration(), () -> {
lease.expire(); state.execution.finish();
});
retainExecution = true;
}
}
@@ -217,18 +279,38 @@ public final class FrostShard implements AbilityEffect, Listener, AutoCloseable
&& current.distanceSquared(state.origin) <= state.settings.range() * state.settings.range();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@EventHandler(priority = EventPriority.MONITOR)
public void acceptedDamage(EntityDamageEvent event) {
var state = damaging;
if (state == null || state.accepted || event.getEntity() != state.target || event.getFinalDamage() <= 0
|| !Double.isFinite(event.getFinalDamage())) return;
if (state == null || state.accepted || event.getEntity() != state.target) return;
var direct = event.getDamageSource().getDirectEntity();
if (direct != state.projectile && (!(event instanceof org.bukkit.event.entity.EntityDamageByEntityEvent byEntity)
|| byEntity.getDamager() != state.projectile)) return;
if (event.isCancelled()) { state.nativeCancelled = true; return; }
if (event.getFinalDamage() <= 0 || !Double.isFinite(event.getFinalDamage())) return;
state.accepted = true;
try { state.execution.acceptedDamage(state.target, state.requested, event.getFinalDamage(), state.projectile,
Map.of("projectile_id", state.projectile.getUniqueId().toString(),
"impact_location", locationData(state.projectile.getLocation()))); }
catch (RuntimeException ignored) { /* An audit failure cannot remove an accepted combat contribution. */ }
state.execution.report(AbilityReport.Type.DAMAGE, event.getEntity(), BigDecimal.valueOf(event.getFinalDamage()));
}
public boolean ownsAcceptedDamage(EntityDamageEvent event) {
var state = damaging;
if (state == null || event.getEntity() != state.target) return false;
var direct = event.getDamageSource().getDirectEntity();
return direct == state.projectile || event instanceof EntityDamageByEntityEvent by
&& by.getDamager() == state.projectile;
}
private static Map<String, Object> locationData(Location location) {
if (location == null || location.getWorld() == null) return Map.of("status", "unavailable");
return Map.of("world_id", location.getWorld().getUID().toString(),
"world_name", location.getWorld().getName(), "x", location.getX(), "y", location.getY(),
"z", location.getZ(), "captured_at", java.time.Instant.now().toString());
}
private static String level(int amplifier) {
return switch (amplifier + 1) {
case 1 -> "I"; case 2 -> "II"; case 3 -> "III"; case 4 -> "IV"; case 5 -> "V";
@@ -18,7 +18,13 @@ import org.bukkit.entity.Entity;
/** Shared cast and explicit effect-observation boundary; never infers effects from feedback. */
public final class AbilityCastEventBridge {
public record Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt, float attackCharge) {
String targetType, Map<String, Object> targetLocation, Instant requestedAt,
float attackCharge, UUID executionId) {
public Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt, float attackCharge) {
this(actionId, context, abilityId, targetId, targetType, targetLocation, requestedAt,
attackCharge, UUID.randomUUID());
}
public Cast(UUID actionId, EventInput.Context context, String abilityId, UUID targetId,
String targetType, Map<String, Object> targetLocation, Instant requestedAt) {
this(actionId, context, abilityId, targetId, targetType, targetLocation, requestedAt, 1.0f);
@@ -229,9 +235,19 @@ public final class AbilityCastEventBridge {
}
public void effectEnded(Cast cast, UUID application, String effectId, String reason) {
effectEnded(cast, application, effectId, reason, Map.of());
}
public void effectEnded(Cast cast, UUID application, String effectId, String reason,
Map<String, Object> evidence) {
if (cast == null) return;
emit(cast, "effect.ended", "ended", Map.of("application_id", application.toString(),
"effect_id", effectId, "reason", reason), application);
try {
var details = new LinkedHashMap<String, Object>(evidence);
details.put("application_id", application.toString());
details.put("effect_id", effectId);
details.put("reason", reason);
emit(cast, "effect.ended", "ended", details, application);
} catch (RuntimeException ignored) { /* Native cleanup is not conditional on audit evidence. */ }
}
private void emit(Cast cast, String type, String outcome, Map<String, Object> extra) {
@@ -244,6 +260,7 @@ public final class AbilityCastEventBridge {
data.put("action_kind", "ability_cast");
data.put("ability_id", cast.abilityId());
data.put("outcome", outcome);
if (cast.abilityId().equals("frost_shard")) data.put("execution_id", cast.executionId().toString());
if (cast.targetId() != null) {
data.put("target_entity_id", cast.targetId().toString());
data.put("target_type", cast.targetType());
@@ -76,11 +76,12 @@ public final class FrostShardSettings implements AutoCloseable {
public FrostShard.Settings settings() { return parse(effectiveValues); }
/** Publish only after the caller returns the durable acknowledgment to the server thread. */
public synchronized void publish(Update update) {
public synchronized boolean publish(Update update) {
Objects.requireNonNull(update);
if (update.sequence() <= publishedSequence) return;
if (update.sequence() <= publishedSequence) return false;
parse(update.values());
effectiveValues = update.values(); publishedSequence = update.sequence();
return true;
}
public CompletionStage<Update> set(String key, String value) {
@@ -1065,8 +1065,11 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
configurationUsage(sender); return;
}
String key = args[1];
var actor = abilityConfigEvents == null ? null : abilityConfigEvents.capture(sender);
String before = frostSettings.value(key);
if (args.length == 2) {
sender.sendMessage(key + "=" + frostSettings.value(key) + " (applies to future Frost Shard casts only)");
if (abilityConfigEvents != null) abilityConfigEvents.read(actor, "frost_shard", key, before);
sender.sendMessage(key + "=" + before + " (applies to future Frost Shard casts only)");
return;
}
java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.FrostShardSettings.Update> operation;
@@ -1080,16 +1083,18 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
try {
nextTick.accept(() -> {
if (closed) return;
if (failure == null) {
frostShard.configure(saved.settings());
boolean applied = failure == null && frostSettings.publish(saved);
if (applied) {
frostShard.configure(frostSettings.settings());
abilities.replace(frostShard.definition());
frostSettings.publish(saved);
if (abilityConfigEvents != null) abilityConfigEvents.changed(actor, "frost_shard", key, before, saved.value());
}
if (!sender.hasPermission(PERMISSION)
|| sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return;
sender.sendMessage(failure == null
? "Saved " + key + "=" + saved.value() + " for future Frost Shard casts; active effects and deadlines are unchanged."
: "Frost Shard configuration save failed; the effective setting is unchanged.");
sender.sendMessage(failure != null
? "Frost Shard configuration save failed; the effective setting is unchanged."
: applied ? "Saved " + key + "=" + saved.value() + " for future Frost Shard casts; active effects and deadlines are unchanged."
: "Saved request was superseded; effective " + key + "=" + frostSettings.value(key) + ".");
});
} catch (RuntimeException rejected) { report(null, "config-response", rejected); }
});