diff --git a/CHANGELOG.md b/CHANGELOG.md index aedfb47..8e4ef2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.7.0 + +- **Who may know whose it is** (D231). `ReachService.mayKnow(viewer, owner, world)` tells another plugin, such as LanternGraves, whether a player may see the owner's name on something they left behind. Stricter than chat, so it fails closed: the owner, either side's bypass, a shared circle, or both players in that world's group right now. Offline owners count only through a circle or bypass; with no circles set up, nobody but the owner. +- Mayor remembers each player's circles and bypass in `known-players.yml` when they join and leave, so the answer works while the owner is offline. A broken file is moved to `known-players.yml.bak` and nobody offline counts as known until they're seen again. +- Tested: unit tests for kids and adults in separate worlds, an adult who left the kids' world or went offline, a shared family circle, a circle-only world, bypass, no circles, an unknown owner, and the file surviving a restart or breaking. Bots on a throwaway Paper 26.3 server with LanternGraves 0.2.0 saw names or "Grave" exactly as the rule says (94/94). Not yet seen in a real game client. + ## 0.6.1 - `mask-for-viewers` no longer gets a warning at start-up saying it isn't a setting. 0.6.0 read and used it all along; only the list of known settings missed it. diff --git a/README.md b/README.md index f68fed5..3d43d61 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,8 @@ if (rules == null || rules.mayReach(from, to)) { /* send it */ } `sharesCircle(viewerHas, to)` is for a viewer who isn't in game, such as someone on a web map. It's true only when they share a circle with `to`. World, world group and bypass don't count, and with no circles set up it's always false. The caller passes the viewer's permissions, read while they're offline, and anything it can't check should answer false. +`mayKnow(viewer, owner, world)` says whether a player may know who left something in a world, such as a grave's name. It's stricter than chat, so it fails closed: the owner, either side's `mayor.bypass`, a shared circle, or both players standing in that world's group right now (unless it's circle-only). An offline owner counts only through a circle or bypass, from what Mayor last saw of them. With no circles set up, nobody but the owner may, and it answers false for anyone Mayor has never seen. Call it from the main thread. For that, Mayor keeps `known-players.yml`: each player's ID with the circle names they held and whether they had `mayor.bypass`, updated when they join and leave and on /mayor reload. Nothing else about them is stored. If you take someone out of a circle while they're offline, Mayor still uses their old circles until they next join; delete their line from the file (with the server stopped) to make it take effect at once. + ## Limits - Signs are readable by anyone who walks past, and a book or named item can be carried to another world. Mayor only checks them when they're written. diff --git a/build.gradle.kts b/build.gradle.kts index 5366b0a..23a7940 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,7 +4,7 @@ plugins { } group = "com.extantape" -version = "0.6.1" +version = "0.7.0" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) diff --git a/src/main/java/com/extantape/mayor/MayorPlugin.java b/src/main/java/com/extantape/mayor/MayorPlugin.java index 8c3d3c0..1587c5b 100644 --- a/src/main/java/com/extantape/mayor/MayorPlugin.java +++ b/src/main/java/com/extantape/mayor/MayorPlugin.java @@ -48,6 +48,8 @@ public record State(Settings settings, Messages messages, Quips quips) { private volatile List problems = List.of(); /** Who each player last messaged or was messaged by, for /r. */ private final Map partners = new ConcurrentHashMap<>(); + /** Each player's circles as last seen, for rules about someone offline (D231). */ + private com.extantape.mayor.rules.KnownPlayers known; @Override public void onEnable() { @@ -56,6 +58,8 @@ public void onEnable() { } Settings defaults = new SettingsLoader(this::getResource).load(null, null, null).settings(); fallback = new State(defaults, new Messages(defaults.messages()), new Quips(List.of(), 0, new Random())); + known = new com.extantape.mayor.rules.KnownPlayers(getDataFolder().toPath(), getLogger()); + known.load(); reload(Bukkit.getConsoleSender()); var plugins = getServer().getPluginManager(); @@ -102,6 +106,7 @@ public boolean reload(CommandSender sender) { new Quips(settings.quips(), settings.nobodyHeard().cooldownSeconds(), new Random())); problems = result.warnings(); registerCirclePermissions(settings.reach()); + rememberOnline(); Reach reach = settings.reach(); getLogger().info(reach.active() ? "Chat rules are on, with " + reach.circles().size() + (reach.circles().size() == 1 ? " circle. " : " circles. ") + settings.filterSummary() @@ -120,6 +125,22 @@ private void registerCirclePermissions(Reach reach) { } } + /** Records what each online player holds now, and saves if anything changed. */ + public void rememberOnline() { + State s = state; + if (s == null || known == null) return; + boolean changed = false; + for (Player p : Bukkit.getOnlinePlayers()) changed |= known.remember(Subject.of(p), s.settings().reach().circles()); + if (changed) known.save(); + } + + /** Records one player as they are now, and saves if anything changed. */ + public void remember(Player player) { + State s = state; + if (s == null || known == null) return; + if (known.remember(Subject.of(player), s.settings().reach().circles())) known.save(); + } + /** The current rules, or null while chat is paused because the config couldn't be read. */ public State state() { return state; @@ -183,4 +204,17 @@ public boolean sharesCircle(java.util.function.Predicate viewerHas, Play return false; } } + + @Override + public boolean mayKnow(Player viewer, UUID owner, String world) { + State s = state; + if (s == null || viewer == null || owner == null) return false; + try { + Player online = Bukkit.getPlayer(owner); + Subject who = online != null ? Subject.of(online) : known == null ? null : known.recall(owner); + return s.settings().reach().mayKnow(Subject.of(viewer), who, world, online != null); + } catch (RuntimeException e) { + return false; + } + } } diff --git a/src/main/java/com/extantape/mayor/api/ReachService.java b/src/main/java/com/extantape/mayor/api/ReachService.java index 5311d45..154c5e0 100644 --- a/src/main/java/com/extantape/mayor/api/ReachService.java +++ b/src/main/java/com/extantape/mayor/api/ReachService.java @@ -20,4 +20,13 @@ public interface ReachService { * it should answer false for anything it can't check. Safe from any thread. */ boolean sharesCircle(java.util.function.Predicate viewerHas, Player to); + + /** + * Whether {@code viewer} may know who {@code owner} is from something the owner left in {@code world}, such as a + * grave's name (D231). Stricter than chat: the owner, either side's bypass, a shared circle, or both standing in + * that world's group now. An offline owner counts only through a circle or bypass, from what Mayor last saw of + * them. False with no circles set up, for an owner Mayor has never seen, or while chat is paused. Call it from + * the main thread. + */ + boolean mayKnow(Player viewer, java.util.UUID owner, String world); } diff --git a/src/main/java/com/extantape/mayor/listen/PlayerListener.java b/src/main/java/com/extantape/mayor/listen/PlayerListener.java index f824652..a268dc7 100644 --- a/src/main/java/com/extantape/mayor/listen/PlayerListener.java +++ b/src/main/java/com/extantape/mayor/listen/PlayerListener.java @@ -9,7 +9,10 @@ import java.util.Map; -/** Tells admins about config problems when they join, and forgets a player's reply partner when they leave. */ +/** + * Tells admins about config problems when they join, and forgets a player's reply partner when they leave. Records each + * player's circles on join and quit, for rules about someone offline (D231). + */ public final class PlayerListener implements Listener { private final MayorPlugin plugin; @@ -20,6 +23,7 @@ public PlayerListener(MayorPlugin plugin) { @EventHandler public void onJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); + plugin.remember(player); if (!player.hasPermission(MayorPlugin.ADMIN)) return; if (plugin.paused()) plugin.tell(player, "admin-paused"); else if (!plugin.problems().isEmpty()) plugin.tell(player, "admin-warnings", Map.of("count", String.valueOf(plugin.problems().size()))); @@ -27,6 +31,7 @@ public void onJoin(PlayerJoinEvent event) { @EventHandler public void onQuit(PlayerQuitEvent event) { + plugin.remember(event.getPlayer()); plugin.partners().remove(event.getPlayer().getUniqueId()); MayorPlugin.State state = plugin.state(); if (state != null) state.quips().forget(event.getPlayer().getUniqueId()); diff --git a/src/main/java/com/extantape/mayor/rules/KnownPlayers.java b/src/main/java/com/extantape/mayor/rules/KnownPlayers.java new file mode 100644 index 0000000..3df621a --- /dev/null +++ b/src/main/java/com/extantape/mayor/rules/KnownPlayers.java @@ -0,0 +1,95 @@ +package com.extantape.mayor.rules; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + +/** + * What Mayor last saw of each player's circles and bypass, so a rule about someone who's offline (whose grave is + * this?) can still be answered (D231). Kept in known-players.yml: one line per player ID with the circle names they + * held and "bypass" if they had mayor.bypass. Nothing else about the player is stored. A player who isn't listed is + * unknown, and every rule treats unknown as no. + */ +public final class KnownPlayers { + public static final String FILE = "known-players.yml"; + private static final String BYPASS_WORD = "bypass"; + + private final Path file; + private final Logger log; + private final Map> held = new ConcurrentHashMap<>(); + + public KnownPlayers(Path folder, Logger log) { + this.file = folder.resolve(FILE); + this.log = log; + } + + /** Reads the file. A broken file is moved aside to known-players.yml.bak and Mayor starts with nobody known. */ + public void load() { + held.clear(); + if (!Files.exists(file)) return; + YamlConfiguration yaml = new YamlConfiguration(); + try { + yaml.loadFromString(Files.readString(file)); + } catch (IOException | InvalidConfigurationException e) { + log.warning(FILE + " couldn't be read, so it was moved to " + FILE + ".bak and nobody offline is known yet: " + e.getMessage()); + try { + Files.move(file, file.resolveSibling(FILE + ".bak"), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ignored) { + // Left in place; the next save overwrites it, which is fine because it couldn't be read anyway. + } + return; + } + for (String key : yaml.getKeys(false)) { + try { + held.put(UUID.fromString(key), new HashSet<>(yaml.getStringList(key))); + } catch (IllegalArgumentException ignored) { + // Not a player ID: skipped. + } + } + } + + /** Records what a player holds now, from the circles in use. Returns true if anything changed. */ + public boolean remember(Subject player, List circles) { + Set now = new HashSet<>(); + for (String circle : circles) if (player.has(Reach.CIRCLE_PERMISSION + circle)) now.add(circle); + if (player.has(Reach.BYPASS)) now.add(BYPASS_WORD); + return !now.equals(held.put(player.id(), now)); + } + + /** The player as last seen, for the rules, or null if Mayor has never seen them. Has no world. */ + public Subject recall(UUID id) { + Set got = held.get(id); + if (got == null) return null; + Set copy = Set.copyOf(got); + return Subject.of(id, "", "", permission -> { + if (permission.equals(Reach.BYPASS)) return copy.contains(BYPASS_WORD); + return permission.startsWith(Reach.CIRCLE_PERMISSION) + && copy.contains(permission.substring(Reach.CIRCLE_PERMISSION.length())); + }); + } + + /** Writes the file through a temporary file, so a crash mid-write never leaves half of it. */ + public void save() { + YamlConfiguration yaml = new YamlConfiguration(); + held.forEach((id, set) -> yaml.set(id.toString(), set.stream().sorted().toList())); + try { + Files.createDirectories(file.getParent()); + Path tmp = file.resolveSibling(FILE + ".tmp"); + Files.writeString(tmp, yaml.saveToString()); + Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + log.warning(FILE + " couldn't be saved: " + e.getMessage()); + } + } +} diff --git a/src/main/java/com/extantape/mayor/rules/Reach.java b/src/main/java/com/extantape/mayor/rules/Reach.java index 8124c02..8961a43 100644 --- a/src/main/java/com/extantape/mayor/rules/Reach.java +++ b/src/main/java/com/extantape/mayor/rules/Reach.java @@ -121,4 +121,24 @@ public boolean reachesWhileAway(java.util.function.Predicate viewer, Sub } return false; } + + /** + * Whether {@code viewer} may know who {@code owner} is from something the owner left in {@code world}, such as a + * grave's name (owner, 2026-11-16, D231). Stricter than chat, so it fails closed: the owner themself, the viewer's + * mayor.bypass, the owner's mayor.bypass, a shared circle, or both players standing in that world's group right now + * (unless it's circle-only). An owner who's offline counts only through a circle or bypass, since where they + * stand isn't known. With no circles set up, nobody else may: there are no groups to follow. An owner Mayor knows + * nothing about ({@code owner} null) counts as no. + * + * @param ownerOnline whether {@code owner} describes a player online now, so their world is real + */ + public boolean mayKnow(Subject viewer, Subject owner, String world, boolean ownerOnline) { + if (owner != null && viewer.id().equals(owner.id())) return true; + if (!active() || owner == null || world == null) return false; + if (viewer.has(BYPASS) || owner.has(BYPASS)) return true; + if (sharedCircle(viewer, owner) != null) return true; + String here = group(world); + return ownerOnline && !circleOnly.contains(here) + && here.equals(group(viewer.world())) && here.equals(group(owner.world())); + } } diff --git a/src/test/java/com/extantape/mayor/rules/MayKnowTest.java b/src/test/java/com/extantape/mayor/rules/MayKnowTest.java new file mode 100644 index 0000000..d2d4e1c --- /dev/null +++ b/src/test/java/com/extantape/mayor/rules/MayKnowTest.java @@ -0,0 +1,114 @@ +package com.extantape.mayor.rules; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Logger; + +import static com.extantape.mayor.rules.Players.circle; +import static com.extantape.mayor.rules.Players.player; +import static org.junit.jupiter.api.Assertions.*; + +/** D231: who may know whose grave it is. Kids and adults in separate worlds, a mixed circle, and no rules at all. */ +class MayKnowTest { + // kids play in "kids" (with its nether), adults in "survival"; "family" is the circle parents and kids share. + private final Reach reach = new Reach(List.of("family", "adults"), Set.of("lobby"), Map.of(), List.of("_nether")); + + @Test + void noCirclesMeansOnlyTheOwnerKnows() { + Reach off = new Reach(List.of(), Set.of(), Map.of(), List.of()); + assertFalse(off.mayKnow(player("kid", "kids"), player("stranger", "survival"), "survival", true)); + Subject kid = player("kid", "kids"); + assertTrue(off.mayKnow(kid, kid, "kids", false)); + } + + @Test + void ownerAlwaysKnowsTheirOwn() { + Subject kid = player("kid", "survival"); + assertTrue(reach.mayKnow(kid, kid, "kids", true)); + } + + @Test + void bothInTheGravesWorldGroupNowKnow() { + assertTrue(reach.mayKnow(player("kid2", "kids_nether"), player("kid", "kids"), "kids", true)); + } + + @Test + void ownerWhoLeftTheWorldOrIsOfflineCountsOnlyByCircle() { + // An adult stranger who died in the kids' world and went back, or logged off: the kids don't see the name. + assertFalse(reach.mayKnow(player("kid", "kids"), player("stranger", "survival", circle("adults")), "kids", true)); + assertFalse(reach.mayKnow(player("kid", "kids"), player("stranger", "kids", circle("adults")), "kids", false)); + } + + @Test + void kidElsewhereDoesNotKnowAnAdultsGrave() { + assertFalse(reach.mayKnow(player("kid", "kids"), player("stranger", "survival", circle("adults")), "survival", true)); + } + + @Test + void adultInAnotherWorldDoesNotKnowAKidsGrave() { + assertFalse(reach.mayKnow(player("stranger", "survival", circle("adults")), player("kid", "kids"), "kids", true)); + } + + @Test + void sharedCircleKnowsAcrossWorlds() { + assertTrue(reach.mayKnow(player("mum", "survival", circle("family")), player("kid", "kids", circle("family")), "kids", true)); + } + + @Test + void circleOnlyWorldNeedsASharedCircle() { + assertFalse(reach.mayKnow(player("a", "lobby"), player("b", "lobby"), "lobby", true)); + assertTrue(reach.mayKnow(player("a", "lobby", circle("family")), player("b", "lobby", circle("family")), "lobby", true)); + } + + @Test + void bypassOnEitherSideKnows() { + assertTrue(reach.mayKnow(player("admin", "survival", Reach.BYPASS), player("kid", "kids"), "kids", true)); + assertTrue(reach.mayKnow(player("kid", "kids_nether"), player("admin", "survival", Reach.BYPASS), "survival", true)); + } + + @Test + void unknownOwnerFailsClosed() { + assertFalse(reach.mayKnow(player("kid", "kids"), null, "kids", true)); + assertFalse(reach.mayKnow(player("kid", "kids"), player("x", "kids"), null, true)); + } + + @Test + void offlineOwnerIsRecalledFromWhatMayorSaw(@TempDir Path dir) { + KnownPlayers known = new KnownPlayers(dir, Logger.getAnonymousLogger()); + Subject kid = player("kid", "kids", circle("family")); + assertTrue(known.remember(kid, reach.circles())); + known.save(); + KnownPlayers again = new KnownPlayers(dir, Logger.getAnonymousLogger()); + again.load(); + Subject recalled = again.recall(kid.id()); + assertNotNull(recalled); + assertTrue(reach.mayKnow(player("mum", "survival", circle("family")), recalled, "kids", false)); + assertFalse(reach.mayKnow(player("stranger", "survival", circle("adults")), recalled, "kids", false)); + assertFalse(reach.mayKnow(player("kid2", "kids"), recalled, "kids", false), "offline, no shared circle: no"); + assertNull(again.recall(UUID.randomUUID())); + } + + @Test + void rememberReportsOnlyChanges(@TempDir Path dir) { + KnownPlayers known = new KnownPlayers(dir, Logger.getAnonymousLogger()); + Subject kid = player("kid", "kids", circle("family")); + assertTrue(known.remember(kid, reach.circles())); + assertFalse(known.remember(kid, reach.circles())); + } + + @Test + void brokenFileIsMovedAsideAndNobodyIsKnown(@TempDir Path dir) throws Exception { + Files.writeString(dir.resolve(KnownPlayers.FILE), "- a list, not a map\n"); + KnownPlayers known = new KnownPlayers(dir, Logger.getAnonymousLogger()); + known.load(); + assertTrue(Files.exists(dir.resolve(KnownPlayers.FILE + ".bak"))); + assertNull(known.recall(UUID.nameUUIDFromBytes("kid".getBytes()))); + } +} diff --git a/test/live/README.md b/test/live/README.md index 64cd13b..ea84ccc 100644 --- a/test/live/README.md +++ b/test/live/README.md @@ -48,6 +48,7 @@ It takes about 4 minutes. The summary lists failures and skipped checks. The ful | Books | A clean edit is kept; a filtered one, or one in a circle-only world with no circle, is refused with an explanation. A filtered word is kept for a player with `mayor.filter.bypass`. | | Nobody heard you | A note from `quips.yml`, a different one next time, and none when someone heard. | | Share (mocked) | Recipients filtered exactly as chat, and cancelled for a no-circle sender in a circle-only world. | +| Graves (D231) | With a LanternGraves jar (`MAYOR_LG_JAR`), real graves from planned deaths: each bot sees the owner's name or "Grave" exactly as an independent model of `mayKnow` says, with the owner in the same group, moved away, sharing a circle, offline, and in a circle-only world. Skipped without the jar. | | LuckPerms | A circle granted or removed takes effect with no relog. | | Config | A broken reload keeps the old rules; a broken config at startup pauses chat and private messages until it's fixed and reloaded. | | Load | 20 more bots, 300 lines in about 15 seconds: all delivered within their circle, TPS, chat latency, no kicks. | diff --git a/test/live/helper/src/main/java/com/extantape/mayor/livetest/LiveTestHelper.java b/test/live/helper/src/main/java/com/extantape/mayor/livetest/LiveTestHelper.java index 262b951..de63b97 100644 --- a/test/live/helper/src/main/java/com/extantape/mayor/livetest/LiveTestHelper.java +++ b/test/live/helper/src/main/java/com/extantape/mayor/livetest/LiveTestHelper.java @@ -31,9 +31,13 @@ public void onDamage(EntityDamageEvent event) { if (event.getEntity() instanceof Player) event.setCancelled(true); } + /** Players a test killed on purpose (mt grave), so their death isn't reported as a bad spawn. */ + private final java.util.Set planned = new java.util.HashSet<>(); + @EventHandler public void onDeath(PlayerDeathEvent event) { - getLogger().info("HRT death " + event.getPlayer().getName()); + String n = event.getPlayer().getName(); + getLogger().info((planned.remove(n) ? "HRT planned death " : "HRT death ") + n); } @Override @@ -60,6 +64,26 @@ public void onEnable() { p.teleportAsync(w.getSpawnLocation()).thenAccept(ok -> getLogger().info("HRT tp " + p.getName() + " " + w.getName() + " " + ok)); return 1; })))) + // mt grave : moves the player offset blocks east of their world's spawn, gives them a + // stick so there's something to leave, and kills them there, for LanternGraves' grave tests (D231). + .then(Commands.literal("grave").then(Commands.argument("player", StringArgumentType.word()) + .then(Commands.argument("offset", com.mojang.brigadier.arguments.IntegerArgumentType.integer(-30, 30)).executes(ctx -> { + Player p = Bukkit.getPlayerExact(StringArgumentType.getString(ctx, "player")); + if (p == null) { + getLogger().info("HRT grave FAILED"); + return 0; + } + int off = com.mojang.brigadier.arguments.IntegerArgumentType.getInteger(ctx, "offset"); + org.bukkit.Location at = p.getWorld().getSpawnLocation().clone().add(off, 0, 0); + p.teleport(at); + p.getInventory().addItem(new org.bukkit.inventory.ItemStack(org.bukkit.Material.STICK)); + planned.add(p.getName()); + Bukkit.getScheduler().runTaskLater(this, () -> { + p.setHealth(0); + getLogger().info("HRT grave " + p.getName() + " " + p.getWorld().getName() + " " + at.getBlockX() + " " + at.getBlockZ()); + }, 5L); + return 1; + })))) .then(Commands.literal("worlds").executes(ctx -> { getLogger().info("HRT worlds " + String.join(",", Bukkit.getWorlds().stream().map(World::getName).toList())); return 1; diff --git a/test/live/run.sh b/test/live/run.sh index 05d343c..b6bda5d 100755 --- a/test/live/run.sh +++ b/test/live/run.sh @@ -56,6 +56,8 @@ motd=Mayor throwaway test server PROPS cp "$WORK/ViaVersion.jar" "$WORK/ViaBackwards.jar" "$WORK/LuckPerms.jar" "$HELPER" "$FAKEMAP" "$SERVER/plugins/" cp "$JAR" "$SERVER/plugins/Mayor.jar" +# Optional: a LanternGraves jar, for the graves part (D231). Without it, that part is skipped. +if [ -n "${MAYOR_LG_JAR:-}" ]; then cp "$MAYOR_LG_JAR" "$SERVER/plugins/LanternGraves.jar"; fi cd "$HERE" LOG=$WORK/$NAME.log echo "== Running the suite (log: $LOG)" diff --git a/test/live/suite.js b/test/live/suite.js index ab230f1..8928a13 100644 --- a/test/live/suite.js +++ b/test/live/suite.js @@ -403,6 +403,74 @@ async function pausedOnBrokenStart() { s.cmd('deop R2'); } +// D231: who sees whose grave. An independent model of Mayor's mayKnow, to compare against: the owner, either side's +// bypass, a shared circle, or (owner online) both standing in the grave's world group, unless it's circle-only. +function knows(viewer, owner, graveWorld, ownerOnline) { + if (viewer === owner) return true; + if (PEOPLE[viewer].bypass || PEOPLE[owner].bypass) return true; + if (shares(viewer, owner)) return true; + const g = group(graveWorld); + return ownerOnline && !circleOnly(graveWorld) && g === group(PEOPLE[viewer].world) && g === group(PEOPLE[owner].world); +} + +/** The grave labels a bot can see now, as {x, text}: LanternGraves shows each player either the name or "Grave". */ +function graveLabels(b) { + return Object.values(b.bot.entities).filter((e) => /text_display/.test(e.name || '')) + .map((e) => ({ x: Math.floor(e.position.x), text: JSON.stringify(e.metadata || []) })) + .filter((l) => /grave|Grave/.test(l.text)); +} + +async function moveTo(n, w) { + PEOPLE[n].world = w; + await s.run(`mt tp ${n} ${w}`, new RegExp(`HRT tp ${n} ${w} true`), 10000); +} + +async function grave(n, offset) { + const w = PEOPLE[n].world; + const m = await s.run(`mt grave ${n} ${offset}`, new RegExp(`HRT grave ${n} (\\S+) (-?\\d+) -?\\d+`), 10000); + await sleep(2500); // respawn + await moveTo(n, w); // back where they were + return m ? +m[2] : null; +} + +/** Checks what each viewer sees on the grave at x, against the model, after LanternGraves' once-a-second refresh. */ +async function seen(owner, graveWorld, x, viewers, ownerOnline, why) { + await sleep(2500); + for (const v of viewers) { + const here = graveLabels(bots[v]).filter((l) => Math.abs(l.x - x) <= 1); + const named = here.some((l) => l.text.includes(`${owner}'s grave`)); + const anon = here.some((l) => !l.text.includes("'s grave")); + const want = knows(v, owner, graveWorld, ownerOnline); + check(`${why}: ${v} sees ${want ? `${owner}'s name` : '"Grave"'}`, here.length === 1 && named === want && anon === !want, + here.map((l) => l.text.slice(0, 80)).join(' | ') || 'no label'); + } +} + +async function graves() { + section('D231: LanternGraves shows a grave\'s owner only to players Mayor\'s groups allow'); + if (!/\[LanternGraves\] Enabling/.test(s.log)) { skip('graves', 'no LanternGraves jar (set MAYOR_LG_JAR)'); return; } + const start = Object.fromEntries(NAMES.map((n) => [n, PEOPLE[n].world])); + // Everyone who looks gathers in meadow (the farm group). + for (const n of ['N3', 'N1', 'R1', 'M1', 'R2']) await moveTo(n, 'meadow'); + await sleep(1500); + const x1 = await grave('N3', 6); + check('a grave is made for a planned death', x1 !== null && /HRT planned death N3/.test(s.log)); + await seen('N3', 'meadow', x1, ['N3', 'N1', 'R1', 'M1', 'R2'], true, 'owner in the same group (farm)'); + await moveTo('N3', 'world'); + await seen('N3', 'meadow', x1, ['N1', 'R1', 'M1', 'R2'], true, 'owner moved to another group'); + const x2 = await grave('R2', -6); + await moveTo('R2', 'world'); + await seen('R2', 'meadow', x2, ['N1', 'R1', 'M1'], true, 'shared circle, owner elsewhere'); + bots.R2.quit(); await sleep(2500); + await seen('R2', 'meadow', x2, ['N1', 'R1', 'M1'], false, 'owner offline'); + bots.R2 = new Bot('R2', +port); await bots.R2.spawned; await moveTo('R2', 'meadow'); + // Circle-only world: being there together isn't enough. + await moveTo('N2', 'hall'); await moveTo('B2', 'hall'); await moveTo('M1', 'hall'); + const x3 = await grave('N2', 4); + await seen('N2', 'hall', x3, ['N2', 'B2', 'M1'], true, 'circle-only world'); + for (const n of NAMES) await moveTo(n, start[n]); +} + (async () => { s = new Server(dir, jar); await s.start(); @@ -433,6 +501,7 @@ async function pausedOnBrokenStart() { await share(); await liveCircles(); await adminCheck(); + await graves(); await brokenReload(); await load(); await pausedOnBrokenStart();