From 372ab99001dcaa97e247e5c847a9131257c5b680 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:51:24 +0000 Subject: [PATCH] Add a staff-only karma command for a ckey karma (Ambassador, Admin) reads the Civ13 coordinator's per-ckey karma snapshot (/shared-records/karma/.json) and shows the admin standing, playtime, kindly/poorly counts and the heaviest givers with their standing, hours, admin-notes flag and warning flags. It answers only in the staff_bot channel or a DM, since karma is hidden from players. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2Tn9GrJ9LZtL9UmHVY --- .github/workflows/status-heartbeat.yml | 6 + docs/shard-group.md | 8 + src/Civ13/KarmaSnapshot.php | 207 ++++++++++++++++++ .../Commands/Civ13GameServerKarma.php | 47 ++++ src/Civ13/MessageServiceManager.php | 1 + tests/local/karma-snapshot.php | 80 +++++++ 6 files changed, 349 insertions(+) create mode 100644 src/Civ13/KarmaSnapshot.php create mode 100644 src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php create mode 100644 tests/local/karma-snapshot.php diff --git a/.github/workflows/status-heartbeat.yml b/.github/workflows/status-heartbeat.yml index 1a42a97d..dbddc394 100644 --- a/.github/workflows/status-heartbeat.yml +++ b/.github/workflows/status-heartbeat.yml @@ -17,6 +17,9 @@ on: - 'src/Civ13/PlayerActivityTotals.php' - 'src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php' - 'tests/local/player-activity-totals.php' + - 'src/Civ13/KarmaSnapshot.php' + - 'src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php' + - 'tests/local/karma-snapshot.php' - '.github/workflows/status-heartbeat.yml' permissions: @@ -49,5 +52,8 @@ jobs: - run: php -l src/Civ13/PlayerActivityTotals.php - run: php -l src/Civ13/MessageCommand/Commands/Civ13GameServerActivity.php - run: php tests/local/player-activity-totals.php + - run: php -l src/Civ13/KarmaSnapshot.php + - run: php -l src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php + - run: php tests/local/karma-snapshot.php - run: php -l src/Civ13/ServerPlayLink.php - run: php tests/local/play-link.php diff --git a/docs/shard-group.md b/docs/shard-group.md index 7d313ad1..05b67753 100644 --- a/docs/shard-group.md +++ b/docs/shard-group.md @@ -41,11 +41,19 @@ DreamDaemon itself. | `update` | `update --region=` | | `hoststatus` | `status --region=`: region name, port, world ready, players, last action, map | | `activity` (Ambassador, Admin) | none: reads `/player-activity-weekly.json` from the server's `region_group` | +| `karma ` (Ambassador, Admin) | none: reads `/shared-records/karma/.json` from the server's `region_group` | `activity` shows the group's weekly player activity totals (active players, new players, sessions, deaths, trips, hours per region). The Civ13 host writes the file beside its activity database; it holds no player names, research or recipe ids. +`karma ` (or a verified Discord ID) shows a player's hidden karma for +staff: admin standing, playtime, kindly and poorly counts (raw and weighted), and +the heaviest givers with their own standing, hours, admin-notes flag and warning +flags. Karma is never shown to players, so the bot answers only in the `staff_bot` +channel or a DM and refuses anywhere else. The Civ13 coordinator writes one file +per ckey whenever that ckey's karma changes; the bot never opens its database. + start, stop, restart and update are accepted within seconds and finish in the script's detached worker; `hoststatus` shows progress. The bot runs as the same user as the group (`civ13`), so no sudo is involved. Roles are the same as for diff --git a/src/Civ13/KarmaSnapshot.php b/src/Civ13/KarmaSnapshot.php new file mode 100644 index 00000000..ad5ad2ce --- /dev/null +++ b/src/Civ13/KarmaSnapshot.php @@ -0,0 +1,207 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13; + +/** + * Hidden karma for one ckey (Civ13 karma plan). The region group's coordinator writes + * `/shared-records/karma/.json` whenever that ckey's karma changes. Karma is staff-only, so the + * command that shows it is for the Admin role and answers only in the staff bot channel or a DM. Read-only: the + * bot never opens the coordinator database. + */ +final class KarmaSnapshot +{ + public const DIR = 'shared-records/karma'; + public const SHOWN_PER_KIND = 10; + private const MAX_BYTES = 1048576; + private const MAX_RATINGS = 2000; + private const STANDINGS = ['trusted', 'good', 'neutral', 'poor', 'bad', 'unknown']; + private const FLAGS = ['burst', 'shared_connection', 'low_weight', 'giver_banned']; + private const STANDING_NAMES = [2 => 'Trusted (+2)', 1 => 'Good (+1)', 0 => 'Neutral (0)', -1 => 'Poor (-1)', -2 => 'Bad (-2)']; + + /** A BYOND ckey as the game stores it. */ + public static function validCkey(string $ckey): bool + { + return preg_match('/^[a-z0-9]{1,64}$/D', $ckey) === 1; + } + + /** Karma is shown only in a DM or in the staff bot channel, never where players can read it. */ + public static function allowedPlace(?string $guildId, ?string $channelId, ?string $staffChannelId): bool + { + if ($guildId === null || $guildId === '') { + return true; + } + + return is_string($staffChannelId) && $staffChannelId !== '' && $channelId === $staffChannelId; + } + + /** The karma for this ckey in this shard group file, or null with a reason in $why. */ + public static function read(string $groupFile, string $ckey, ?string &$why = null): ?array + { + $why = null; + if (! self::validCkey($ckey)) { + $why = 'that is not a valid ckey'; + + return null; + } + if ($groupFile === '') { + $why = 'this server has no region group'; + + return null; + } + $group = self::json($groupFile, 1048576); + if (! is_array($group) || ! is_string($group['root'] ?? null) || $group['root'] === '') { + $why = 'the region group file is unreadable'; + + return null; + } + $raw = self::json(rtrim($group['root'], '/\\').'/'.self::DIR.'/'.$ckey.'.json', self::MAX_BYTES); + if (! is_array($raw)) { + $why = 'no karma recorded for that ckey'; + + return null; + } + $karma = self::clean($raw); + if ($karma['ckey'] !== $ckey) { + $why = 'the karma file does not belong to that ckey'; + + return null; + } + + return $karma; + } + + /** Keep only the expected fields, with safe values. */ + public static function clean(array $raw): array + { + $num = static fn (mixed $value): float => is_int($value) || (is_float($value) && is_finite($value)) ? round((float) $value, 2) : 0.0; + $count = static fn (mixed $value): int => is_int($value) ? max(0, $value) : 0; + $date = static fn (mixed $value): string => is_string($value) && preg_match('/^[0-9: UTC-]{10,24}$/D', $value) === 1 ? $value : ''; + $ckey = static fn (mixed $value): string => is_string($value) && self::validCkey($value) ? $value : ''; + + $standing = null; + if (is_array($raw['standing'] ?? null) && is_int($raw['standing']['value'] ?? null) && isset(self::STANDING_NAMES[$raw['standing']['value']])) { + $standing = [ + 'value' => $raw['standing']['value'], + 'reason' => self::text($raw['standing']['reason'] ?? '', 300), + 'author' => $ckey($raw['standing']['author'] ?? ''), + 'at' => $date($raw['standing']['at'] ?? ''), + ]; + } + $summary = is_array($raw['summary'] ?? null) ? $raw['summary'] : []; + $ratings = []; + foreach (is_array($raw['ratings'] ?? null) ? array_slice($raw['ratings'], 0, self::MAX_RATINGS) : [] as $row) { + if (! is_array($row) || ! in_array($row['kind'] ?? null, ['kindly', 'poorly'], true) || ($giver = $ckey($row['giver'] ?? '')) === '') { + continue; + } + $ratings[] = [ + 'giver' => $giver, + 'kind' => $row['kind'], + 'weight' => max(0.0, $num($row['weight'] ?? 0)), + 'giver_standing' => in_array($row['giver_standing'] ?? null, self::STANDINGS, true) ? $row['giver_standing'] : 'unknown', + 'giver_hours' => max(0.0, $num($row['giver_hours'] ?? 0)), + 'giver_notes' => ($row['giver_notes'] ?? false) === true, + 'flags' => array_values(array_intersect(self::FLAGS, is_array($row['flags'] ?? null) ? $row['flags'] : [])), + 'at' => $date($row['at'] ?? ''), + 'note' => self::text($row['note'] ?? '', 1000), + ]; + } + // Heaviest first, so the shown rows are the ones that count most. + usort($ratings, static fn (array $a, array $b): int => $b['weight'] <=> $a['weight'] ?: strcmp($a['giver'], $b['giver'])); + + return [ + 'ckey' => $ckey($raw['ckey'] ?? ''), + 'generated' => $date($raw['generated'] ?? ''), + 'standing' => $standing, + 'hours' => max(0.0, $num($raw['hours'] ?? 0)), + 'summary' => [ + 'kindly' => $count($summary['kindly'] ?? 0), + 'poorly' => $count($summary['poorly'] ?? 0), + 'kindly_weighted' => max(0.0, $num($summary['kindly_weighted'] ?? 0)), + 'poorly_weighted' => max(0.0, $num($summary['poorly_weighted'] ?? 0)), + 'per10h' => $num($summary['per10h'] ?? 0), + ], + 'ratings' => $ratings, + ]; + } + + /** A Discord message for staff. */ + public static function describe(array $karma): string + { + $s = $karma['summary']; + $lines = ["**Karma for {$karma['ckey']}**".($karma['generated'] !== '' ? " ({$karma['generated']})" : '')]; + if ($standing = $karma['standing']) { + $by = $standing['author'] !== '' ? " by {$standing['author']}" : ''; + $on = $standing['at'] !== '' ? " on {$standing['at']}" : ''; + $why = $standing['reason'] !== '' ? ": {$standing['reason']}" : ''; + $lines[] = 'Admin standing: '.self::STANDING_NAMES[$standing['value']].$by.$on.$why; + } else { + $lines[] = 'Admin standing: not set.'; + } + $lines[] = "Playtime: {$karma['hours']} h (alive, awake and connected)."; + $lines[] = "Kindly {$s['kindly']} (weighted {$s['kindly_weighted']}), poorly {$s['poorly']} (weighted {$s['poorly_weighted']}). Net per 10 h played: {$s['per10h']}."; + foreach (['kindly' => 'Remembered kindly by', 'poorly' => 'Remembered poorly by'] as $kind => $title) { + $rows = array_values(array_filter($karma['ratings'], static fn (array $row): bool => $row['kind'] === $kind)); + if (! $rows) { + continue; + } + $lines[] = "**$title** (".count($rows).')'; + foreach (array_slice($rows, 0, self::SHOWN_PER_KIND) as $row) { + $extra = [$row['giver_standing'], $row['giver_hours'].' h', 'weight '.$row['weight']]; + if ($row['giver_notes']) { + $extra[] = 'has admin notes'; + } + foreach ($row['flags'] as $flag) { + $extra[] = str_replace('_', ' ', $flag); + } + $line = "- {$row['giver']} (".implode(', ', $extra).')'.($row['at'] !== '' ? " {$row['at']}" : ''); + if ($row['note'] !== '') { + $line .= ': '.self::text($row['note'], 120); + } + $lines[] = $line; + } + if (count($rows) > self::SHOWN_PER_KIND) { + $lines[] = '- and '.(count($rows) - self::SHOWN_PER_KIND).' more (see the in-game Karma panel).'; + } + } + + return implode("\n", $lines); + } + + /** Plain text on one line: no mentions, markdown or links survive. */ + private static function text(mixed $value, int $limit): string + { + if (! is_string($value)) { + return ''; + } + $value = preg_replace('/[\x00-\x1F\x7F]+/u', ' ', $value) ?? ''; + $value = str_replace(['@', '`', '*', '_', '~', '|', '>', '<', '[', ']', '(', ')', '#'], ' ', $value); + $value = trim(preg_replace('/\s+/u', ' ', $value) ?? ''); + + return mb_strlen($value) > $limit ? rtrim(mb_substr($value, 0, $limit - 1)).'…' : $value; + } + + private static function json(string $path, int $limit): mixed + { + clearstatcache(true, $path); + $bytes = @is_file($path) ? @file_get_contents($path, false, null, 0, $limit + 1) : false; + if (! is_string($bytes) || strlen($bytes) > $limit) { + return null; + } + try { + return json_decode($bytes, true, 16, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return null; + } + } +} diff --git a/src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php b/src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php new file mode 100644 index 00000000..8ee38084 --- /dev/null +++ b/src/Civ13/MessageCommand/Commands/Civ13GameServerKarma.php @@ -0,0 +1,47 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13\MessageCommand\Commands; + +use Civ13\KarmaSnapshot; +use Civ13\MessageCommand\Civ13GameServerMessageCommand; +use Discord\Parts\Channel\Message; +use React\Promise\PromiseInterface; + +/** + * Handles the "karma" command: a ckey's hidden karma for staff (admin standing, playtime, who rated them and how + * those givers stand). Admin only, and only in the staff bot channel or a DM. + */ +class Civ13GameServerKarma extends Civ13GameServerMessageCommand +{ + /** + * @inheritDoc + */ + public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface + { + if (! KarmaSnapshot::allowedPlace($message->guild_id, $message->channel_id, $this->civ13->channel_ids['staff_bot'] ?? null)) { + return $this->civ13->reply($message, 'Karma is staff-only: ask in the staff bot channel or in a DM.'); + } + if (! $id = self::messageWithoutCommand($command, $message_filtered, true, true)) { + return $this->civ13->reply($message, 'Invalid format! Please use the format: '.$command.' `ckey`'); + } + // A Discord ID means its verified ckey, like ckeyinfo. + $ckey = is_numeric($id) ? ($this->civ13->verifier->getVerifiedItem($id)['ss13'] ?? '') : $id; + if (! is_string($ckey) || $ckey === '') { + return $this->civ13->reply($message, "No verified ckey for Discord ID `$id`."); + } + $karma = KarmaSnapshot::read($this->gameserver->regionGroupFile(), $ckey, $why); + + return $this->civ13->reply($message, $karma === null ? "No karma for `$ckey`: $why." : KarmaSnapshot::describe($karma), "karma-$ckey.txt", true); + } +} diff --git a/src/Civ13/MessageServiceManager.php b/src/Civ13/MessageServiceManager.php index 87dbf145..44744f6e 100644 --- a/src/Civ13/MessageServiceManager.php +++ b/src/Civ13/MessageServiceManager.php @@ -313,6 +313,7 @@ function (Message $message, string $command, array $message_filtered) use (&$gam ->offsetSet("{$gameserver->key}manage", new Commands\Civ13GameServerManage($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}hoststatus", new Commands\Civ13GameServerHostStatus($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}activity", new Commands\Civ13GameServerActivity($this->civ13, $gameserver), ['Ambassador', 'Admin']) + ->offsetSet("{$gameserver->key}karma", new Commands\Civ13GameServerKarma($this->civ13, $gameserver), ['Ambassador', 'Admin']) ->offsetSet("{$gameserver->key}mapswap", new Commands\Civ13GameServerMapSwap($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}panic", new Commands\Civ13GameServerPanic($this->civ13, $gameserver), ['Ambassador']) ->offsetSet("{$gameserver->key}ban", new Commands\Civ13GameServerBan($this->civ13, $gameserver), ['Admin']) diff --git a/tests/local/karma-snapshot.php b/tests/local/karma-snapshot.php new file mode 100644 index 00000000..a79b919e --- /dev/null +++ b/tests/local/karma-snapshot.php @@ -0,0 +1,80 @@ + $root, 'regions' => [['id' => 'gaia']]])); +$file = $root.'/'.KarmaSnapshot::DIR.'/alice.json'; + +// Only a DM or the staff bot channel may show karma; with no staff channel configured, only DMs. +check(KarmaSnapshot::allowedPlace(null, '5', '9'), 'A DM was refused'); +check(KarmaSnapshot::allowedPlace('1', '9', '9'), 'The staff bot channel was refused'); +check(! KarmaSnapshot::allowedPlace('1', '5', '9'), 'A public channel was allowed'); +check(! KarmaSnapshot::allowedPlace('1', '5', null) && ! KarmaSnapshot::allowedPlace('1', '', ''), 'A guild channel was allowed without a staff channel'); + +// Bad ckeys, no group, nothing recorded, broken and mismatched files. +check(KarmaSnapshot::read($group, '../alice', $why) === null && $why === 'that is not a valid ckey', 'A path in the ckey was accepted'); +check(KarmaSnapshot::read('', 'alice', $why) === null && $why === 'this server has no region group', 'A server without a group was not reported'); +check(KarmaSnapshot::read($group, 'alice', $why) === null && $why === 'no karma recorded for that ckey', 'A missing karma file was not reported'); +file_put_contents($file, '{not json'); +check(KarmaSnapshot::read($group, 'alice') === null, 'A broken karma file was read'); +file_put_contents($file, json_encode(['ckey' => 'bob'])); +check(KarmaSnapshot::read($group, 'alice', $why) === null && str_contains($why, 'does not belong'), 'Another ckey\'s karma was shown'); + +// A full snapshot: bad rows dropped, unknown fields and flags dropped, heaviest givers first, text made safe. +$ratings = [ + ['giver' => 'carol', 'kind' => 'kindly', 'weight' => 0.4, 'giver_standing' => 'good', 'giver_hours' => 40, 'giver_notes' => false, 'flags' => [], 'at' => '2026-11-18', 'note' => 'Helped me <@123> build **a house**'], + ['giver' => 'dave', 'kind' => 'kindly', 'weight' => 1.2, 'giver_standing' => 'trusted', 'giver_hours' => 300, 'giver_notes' => false, 'flags' => ['made_up'], 'at' => '2026-11-17'], + ['giver' => 'eve', 'kind' => 'poorly', 'weight' => 0.0, 'giver_standing' => 'bad', 'giver_hours' => 2, 'giver_notes' => true, 'flags' => ['burst', 'giver_banned'], 'at' => '2026-11-19'], + ['giver' => 'Not A Ckey', 'kind' => 'kindly', 'weight' => 5], + ['giver' => 'frank', 'kind' => 'meh', 'weight' => 5], +]; +for ($i = 0; $i < 12; $i++) { + $ratings[] = ['giver' => "g$i", 'kind' => 'kindly', 'weight' => 0.01, 'giver_standing' => 'neutral', 'giver_hours' => 1]; +} +file_put_contents($file, json_encode([ + 'ckey' => 'alice', 'generated' => '2026-11-19 05:00 UTC', 'ip' => '1.2.3.4', + 'standing' => ['value' => -1, 'reason' => 'Griefed @everyone', 'author' => 'valzargaming', 'at' => '2026-11-18'], + 'hours' => 12.345, + 'summary' => ['kindly' => 14, 'poorly' => 1, 'kindly_weighted' => 1.72, 'poorly_weighted' => 0, 'per10h' => 1.39], + 'ratings' => $ratings, +])); +$karma = KarmaSnapshot::read($group, 'alice'); +check(is_array($karma) && ! isset($karma['ip']), 'Unexpected fields were kept'); +check(count($karma['ratings']) === 15, 'Bad rating rows were kept: '.count($karma['ratings'])); +check($karma['ratings'][0]['giver'] === 'dave' && $karma['ratings'][0]['flags'] === [], 'Givers were not sorted by weight or an unknown flag was kept'); +check($karma['hours'] === 12.35, 'Hours were not rounded'); +$text = KarmaSnapshot::describe($karma); +check(str_contains($text, 'Admin standing: Poor (-1) by valzargaming on 2026-11-18: Griefed everyone'), 'Standing line changed: '.$text); +check(str_contains($text, 'Playtime: 12.35 h'), 'Playtime line missing'); +check(str_contains($text, 'Kindly 14 (weighted 1.72), poorly 1 (weighted 0)'), 'Summary line changed'); +check(str_contains($text, '- eve (bad, 2 h, weight 0, has admin notes, burst, giver banned) 2026-11-19'), 'Poorly row changed: '.$text); +check(str_contains($text, 'and 4 more'), 'Long lists were not cut'); +check(! str_contains($text, '@') && ! str_contains($text, '**a house**') && ! str_contains($text, '<'), 'A mention or markdown reached the message: '.$text); + +// No standing set, and an oversized file is refused. +file_put_contents($file, json_encode(['ckey' => 'alice', 'standing' => ['value' => 7]])); +check(str_contains(KarmaSnapshot::describe(KarmaSnapshot::read($group, 'alice')), 'Admin standing: not set.'), 'A bad standing was shown'); +file_put_contents($file, str_repeat(' ', 1048600).'{}'); +check(KarmaSnapshot::read($group, 'alice') === null, 'An oversized karma file was read'); + +unlink($file); +rmdir($root.'/'.KarmaSnapshot::DIR); +rmdir($root.'/shared-records'); +unlink($group); +rmdir($root); +echo "PASS karma snapshot\n";