From 02ef9f495418e270da455c9bff946ae74f3df71d Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Mon, 26 Oct 2026 18:07:05 -0400 Subject: [PATCH] feat(bot): add staff-only /debug command for previewing and reposting bot messages --- src/bot/AGENTS.md | 17 +- src/bot/commands/debug.ts | 316 ++++++++++++++++++++++++++ src/bot/commands/index.ts | 2 + src/bot/config.ts | 2 + src/bot/lib/debugActions.ts | 431 ++++++++++++++++++++++++++++++++++++ 5 files changed, 767 insertions(+), 1 deletion(-) create mode 100644 src/bot/commands/debug.ts create mode 100644 src/bot/lib/debugActions.ts diff --git a/src/bot/AGENTS.md b/src/bot/AGENTS.md index 0abf055d..d59a4725 100644 --- a/src/bot/AGENTS.md +++ b/src/bot/AGENTS.md @@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc ## Env -Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`. +Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `DISCORD_DEBUG_CHANNEL_ID` (sandbox channel for `/debug run ... mode:sandbox`; unset disables sandbox), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`. ## Structure @@ -27,6 +27,7 @@ bot/ remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger) rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call) discordPresence.ts # /discord-presence (guild-only, discord:rp:update; view/edit/clear the bot's Rich Presence via a prefilled modal) + debug.ts # /debug (guild-only, staff only; list | run preview|sandbox|live | inspect | delete, see "Feature flow: debug") events/ interactionCreate.ts # Routes ptf-att: RSVP button interactions @@ -46,6 +47,7 @@ bot/ discordPresence.ts # Poll the discord-presence Global → reconcile the bot's live Rich Presence (in-memory last-applied diff) lib/ + debugActions.ts # /debug action registry: each action builds the production message and sends it live roles.ts # isStaff check resolve.ts # discordId ↔ Payload user lookups transferMessaging.ts # Transfer embed builders + delivery keys @@ -65,6 +67,19 @@ bot/ `/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. **Edit mode** (`edit=true`): instead of posting, opens a modal prefilled with the target entry's raw markdown so staff can make last-minute copy tweaks right in Discord; submit renders the edited text through the same pipeline and posts it. One-shot by design: the edit shapes only the post about to happen, `CHANGELOG.md` (baked into the deployed image) is never written back. Single-version targets only (ranges are rejected ephemerally), entries over the 4000-char modal input cap refuse edit mode with a pointer to the file. The modal must be the first response, so the edit path checks staff and shows the modal WITHOUT deferring (same pattern as `/announce`); submits route through `bot/index.ts` on the `ptf-changelog-edit:` custom-id prefix and re-check staff. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become Discord markdown headings (`### `, the deepest level Discord renders), bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger. +## Feature flow: debug + +`/debug` (guild-only, `isStaff`) re-renders or re-sends bot messages through the production render and send code, so a test exercises what actually ships. Subcommands: `list`, `run action target mode`, `inspect action target`, `delete action target`. + +- **preview** (default): ephemeral. Shows the exact embed, with buttons stripped. Writes nothing. +- **sandbox**: posts to `DISCORD_DEBUG_CHANNEL_ID` with mentions suppressed. Writes nothing. Refused with a message when that env var is unset. +- **live**: posts to the real channel after a Confirm button (30s timeout). Supported by `rollcall` (`method=edit` edits the stored message in place, `method=repost` posts fresh and links it), `modlist`, `npc-dispatch`, `achievement`, and `changelog` (posts to the releases channel). Live posts do not change one-shot markers or hashes except through the rollcall path. +- **delete**: removes the tracked message after Confirm and clears its stored id. Keeps the one-shot markers, so a deleted message is not reposted automatically. + +Preview-only actions (no live send): `imminent` (live thread pings would reach attendees), `ready-reminders`, `friday-notice` (a live post would create a real dedup token), `evaluations` (shows the first recipient's DM with a recipient count), `notification`, and `transfer`. Preview omits buttons, so debug output never exposes a live decision control. + +Actions live in `bot/lib/debugActions.ts`. Each `build` receives the client and returns the message the production path sends. The render helpers they reuse are exported from `services/missionEmbeds.ts`, `services/npcEventAnnouncements.ts`, `services/imminentReminders.ts`, `services/readyReminders.ts`, `services/evaluationReminders.ts`, `services/notificationBridge.ts`, `services/fridayOpsNotice.ts`, `services/transferDelivery.ts`, and `commands/changelog.ts`. + ## Feature flow: attendance Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`). Staff can force one outside the lead-time window with `/rollcall [mission]` (ID, name, or code name; omit to target the next upcoming Scheduled unit op): `forceRollCall` in `missionEmbeds.ts` re-renders the live message or posts a fresh one (even after a manual deletion), bypassing only the 3-day gate; target lookup/validation lives in `src/lib/intelligence/rollCall.ts`. diff --git a/src/bot/commands/debug.ts b/src/bot/commands/debug.ts new file mode 100644 index 00000000..0b38e92a --- /dev/null +++ b/src/bot/commands/debug.ts @@ -0,0 +1,316 @@ +import { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ComponentType, + MessageFlags, + SlashCommandBuilder, + type ChatInputCommandInteraction, + type Client, +} from "discord.js"; +import type { Payload } from "payload"; +import type { BotCommand } from "./index"; +import { botConfig } from "@/bot/config"; +import { isStaff } from "@/bot/lib/roles"; +import { + debugActions, + findDebugAction, + type DebugAction, + type DebugMode, + type OutboundMessage, +} from "@/bot/lib/debugActions"; + +const CONFIRM_TIMEOUT_MS = 30_000; + +const actionChoices = debugActions.map((action) => ({ name: action.name, value: action.name })); + +const formatError = (error: unknown): string => + error instanceof Error ? error.message : "Unknown error"; + +const stripComponents = (message: OutboundMessage): OutboundMessage => ({ + content: message.content, + embeds: message.embeds, + files: message.files, +}); + +/** + * Asks for a button press before a live change. Returns true only when the + * caller clicks Confirm within the timeout; anything else cancels. + */ +const confirmLive = async ( + interaction: ChatInputCommandInteraction, + prompt: string, +): Promise => { + const confirm = new ButtonBuilder() + .setCustomId(`ptf-debug-confirm:${interaction.id}`) + .setStyle(ButtonStyle.Danger) + .setLabel("Confirm"); + const cancel = new ButtonBuilder() + .setCustomId(`ptf-debug-cancel:${interaction.id}`) + .setStyle(ButtonStyle.Secondary) + .setLabel("Cancel"); + const row = new ActionRowBuilder().addComponents(confirm, cancel); + + const reply = await interaction.editReply({ content: prompt, components: [row] }); + try { + const press = await reply.awaitMessageComponent({ + componentType: ComponentType.Button, + filter: (press) => press.user.id === interaction.user.id, + time: CONFIRM_TIMEOUT_MS, + }); + await press.update({ content: "Working...", components: [] }); + return press.customId === `ptf-debug-confirm:${interaction.id}`; + } catch { + await interaction.editReply({ content: "Timed out. Nothing was changed.", components: [] }); + return false; + } +}; + +const runPreview = async ( + interaction: ChatInputCommandInteraction, + payload: Payload, + client: Client, + action: DebugAction, + target: string | undefined, +): Promise => { + const message = stripComponents(await action.build(client, payload, target)); + const header = `Preview of \`${action.name}\`. Nothing was posted or stored. Buttons are omitted in debug output.`; + await interaction.editReply({ + content: message.content ? `${header}\n\n${message.content}` : header, + embeds: message.embeds, + files: message.files, + }); +}; + +const runSandbox = async ( + interaction: ChatInputCommandInteraction, + payload: Payload, + client: Client, + action: DebugAction, + target: string | undefined, +): Promise => { + const debugChannelId = botConfig.debugChannelId; + if (!debugChannelId) { + await interaction.editReply( + "Sandbox is disabled because DISCORD_DEBUG_CHANNEL_ID is not set. Use preview or live.", + ); + return; + } + const message = stripComponents(await action.build(client, payload, target)); + const channel = await client.channels.fetch(debugChannelId); + if (!channel || !("send" in channel)) { + throw new Error(`Debug channel ${debugChannelId} is not a text channel.`); + } + await ( + channel as unknown as { + send(options: OutboundMessage & { allowedMentions: { parse: never[] } }): Promise; + } + ).send({ + content: message.content, + embeds: message.embeds, + files: message.files, + allowedMentions: { parse: [] }, + }); + await interaction.editReply( + `Sent a sandbox copy of \`${action.name}\` to <#${debugChannelId}>. Nothing stored changed.`, + ); +}; + +const runLive = async ( + interaction: ChatInputCommandInteraction, + payload: Payload, + client: Client, + action: DebugAction, + target: string | undefined, + method: "edit" | "repost" | undefined, +): Promise => { + if (!action.live) { + await interaction.editReply( + `\`${action.name}\` has no live mode. Use preview or sandbox instead.`, + ); + return; + } + const confirmed = await confirmLive( + interaction, + `This posts \`${action.name}\` to the **real** channel and may update stored state. Confirm?`, + ); + if (!confirmed) { + await interaction.editReply({ + content: `Cancelled. Nothing was posted for \`${action.name}\`.`, + components: [], + }); + return; + } + const result = await action.live(client, payload, target, { method }); + await interaction.editReply({ content: result, components: [] }); +}; + +const runDelete = async ( + interaction: ChatInputCommandInteraction, + payload: Payload, + client: Client, + action: DebugAction, + target: string | undefined, +): Promise => { + if (!action.remove) { + await interaction.editReply(`\`${action.name}\` has no tracked message to delete.`); + return; + } + const confirmed = await confirmLive( + interaction, + `This **deletes** the tracked \`${action.name}\` message from the real channel. Confirm?`, + ); + if (!confirmed) { + await interaction.editReply({ content: "Cancelled. Nothing was deleted.", components: [] }); + return; + } + const result = await action.remove(client, payload, target); + await interaction.editReply({ content: result, components: [] }); +}; + +const runList = (): string => + debugActions + .map((action) => { + const modes = ["preview", action.live ? "live" : null, "sandbox"] + .filter(Boolean) + .join(", "); + return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`; + }) + .join("\n\n"); + +const requireAction = (name: string): DebugAction => { + const action = findDebugAction(name); + if (!action) throw new Error(`Unknown debug action "${name}".`); + return action; +}; + +export const debugCommand: BotCommand = { + builder: new SlashCommandBuilder() + .setName("debug") + .setDescription("Preview, sandbox, or live-repost bot messages (staff only)") + .addSubcommand((sub) => + sub.setName("list").setDescription("List the debuggable bot actions"), + ) + .addSubcommand((sub) => + sub + .setName("run") + .setDescription("Render or send a bot message for a target") + .addStringOption((option) => + option + .setName("action") + .setDescription("Which bot message to run") + .setRequired(true) + .addChoices(...actionChoices), + ) + .addStringOption((option) => + option + .setName("target") + .setDescription("Mission ID/name/code name, or the record ID the action expects"), + ) + .addStringOption((option) => + option + .setName("mode") + .setDescription("preview (default, ephemeral), sandbox (debug channel), or live (real)") + .addChoices( + { name: "preview", value: "preview" }, + { name: "sandbox", value: "sandbox" }, + { name: "live", value: "live" }, + ), + ) + .addStringOption((option) => + option + .setName("method") + .setDescription("Live roll-call only: edit the existing message, or repost a fresh one") + .addChoices( + { name: "edit", value: "edit" }, + { name: "repost", value: "repost" }, + ), + ), + ) + .addSubcommand((sub) => + sub + .setName("inspect") + .setDescription("Show the stored bot-side state for a target") + .addStringOption((option) => + option + .setName("action") + .setDescription("Which bot message") + .setRequired(true) + .addChoices(...actionChoices), + ) + .addStringOption((option) => option.setName("target").setDescription("Target")), + ) + .addSubcommand((sub) => + sub + .setName("delete") + .setDescription("Delete a tracked bot message (live, with confirmation)") + .addStringOption((option) => + option + .setName("action") + .setDescription("Which bot message") + .setRequired(true) + .addChoices(...actionChoices), + ) + .addStringOption((option) => option.setName("target").setDescription("Target")), + ) as SlashCommandBuilder, + execute: async (interaction, payload) => { + if (!interaction.inGuild() || !interaction.guild) { + await interaction.reply({ + content: "This command only works in a server.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + const member = await interaction.guild.members.fetch(interaction.user.id); + if (!(await isStaff(member, payload))) { + await interaction.reply({ + content: "You don't have permission to use debug.", + flags: MessageFlags.Ephemeral, + }); + return; + } + + const subcommand = interaction.options.getSubcommand(); + if (subcommand === "list") { + await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral }); + return; + } + + await interaction.deferReply({ flags: MessageFlags.Ephemeral }); + const client = interaction.client as Client; + const actionName = interaction.options.getString("action", true); + const target = interaction.options.getString("target")?.trim() || undefined; + + try { + const action = requireAction(actionName); + + if (subcommand === "run") { + const mode = (interaction.options.getString("mode") ?? "preview") as DebugMode; + const method = interaction.options.getString("method") as "edit" | "repost" | null; + if (mode === "preview") await runPreview(interaction, payload, client, action, target); + else if (mode === "sandbox") await runSandbox(interaction, payload, client, action, target); + else await runLive(interaction, payload, client, action, target, method ?? undefined); + return; + } + + if (subcommand === "inspect") { + if (!action.inspect) { + await interaction.editReply(`\`${action.name}\` has no stored state to inspect.`); + return; + } + const state = await action.inspect(payload, target); + await interaction.editReply( + "```json\n" + JSON.stringify(state, null, 2) + "\n```", + ); + return; + } + + if (subcommand === "delete") { + await runDelete(interaction, payload, client, action, target); + } + } catch (error) { + await interaction.editReply(`Debug failed: ${formatError(error)}`); + } + }, +}; diff --git a/src/bot/commands/index.ts b/src/bot/commands/index.ts index cce6c280..0c27cdea 100644 --- a/src/bot/commands/index.ts +++ b/src/bot/commands/index.ts @@ -8,6 +8,7 @@ import { changelogCommand } from "./changelog"; import { remindEvaluationsCommand } from "./remindEvaluations"; import { rollCallCommand } from "./rollcall"; import { discordPresenceCommand } from "./discordPresence"; +import { debugCommand } from "./debug"; export interface BotCommand { builder: SlashCommandBuilder; @@ -29,4 +30,5 @@ export const commands: BotCommand[] = [ remindEvaluationsCommand, rollCallCommand, discordPresenceCommand, + debugCommand, ]; diff --git a/src/bot/config.ts b/src/bot/config.ts index 5e70697f..9c05fa89 100644 --- a/src/bot/config.ts +++ b/src/bot/config.ts @@ -10,6 +10,7 @@ export interface BotConfig { changelogChannelId: string | null; announceMentionRoleId: string | null; npcEventChannelId: string | null; + debugChannelId: string | null; attendancePollMs: number; notificationPollMs: number; evaluationPollMs: number; @@ -61,6 +62,7 @@ export const botConfig: BotConfig = { changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"), announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"), npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"), + debugChannelId: optional("DISCORD_DEBUG_CHANNEL_ID"), attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000), notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000), evaluationPollMs: pollMs("DISCORD_EVALUATION_POLL_MS", 60_000), diff --git a/src/bot/lib/debugActions.ts b/src/bot/lib/debugActions.ts new file mode 100644 index 00000000..5ef3b321 --- /dev/null +++ b/src/bot/lib/debugActions.ts @@ -0,0 +1,431 @@ +import { + AttachmentBuilder, + EmbedBuilder, + type ActionRowBuilder, + type ButtonBuilder, + type Client, + type TextBasedChannelFields, +} from "discord.js"; +import { readFileSync } from "node:fs"; +import type { Payload } from "payload"; +import { botConfig } from "@/bot/config"; +import { + CHANGELOG_PATH, + postVersion, + renderVersionEmbeds, +} from "@/bot/commands/changelog"; +import { + buildModlistMessage, + buildRollCallMessage, + forceRollCall, + postEmbed, + postModlistMessage, + resolveModlist, +} from "@/bot/services/missionEmbeds"; +import { buildEmbed as buildNpcEmbed } from "@/bot/services/npcEventAnnouncements"; +import { renderReminderEmbed as renderImminentEmbed } from "@/bot/services/imminentReminders"; +import { renderReminderEmbed as renderReadyEmbed } from "@/bot/services/readyReminders"; +import { renderReminderEmbed as renderEvaluationEmbed } from "@/bot/services/evaluationReminders"; +import { renderNotificationEmbed } from "@/bot/services/notificationBridge"; +import { + getSideOpsChannel, + renderNotice, + resolveZeusRoleId, +} from "@/bot/services/fridayOpsNotice"; +import { contextFor } from "@/bot/services/transferDelivery"; +import { requestEmbed, transferDecisionRow } from "@/bot/lib/transferMessaging"; +import { resolveChangelog } from "@/bot/lib/changelogRender"; +import { + achievementWindowLabel, + groupAchievementsForAnnouncement, + renderAchievementAnnouncement, + type AchievementAnnouncementRow, +} from "@/bot/lib/achievementRender"; +import { computeEvaluationReminderPlan } from "@/lib/evaluations/reminders"; +import { getNextUpcomingScheduledMission, resolveMissionByRef } from "@/lib/intelligence/rollCall"; +import type { + AssignmentTransfer, + GameEventLog, + Mission, + UserNotification, +} from "@/payload-types"; + +export type DebugMode = "preview" | "sandbox" | "live"; + +/** The exact message a production path would send, before any send happens. */ +export interface OutboundMessage { + content?: string; + embeds: EmbedBuilder[]; + components?: ActionRowBuilder[]; + files?: AttachmentBuilder[]; +} + +export interface LiveOptions { + /** Roll-call only: edit the live message in place, or post a fresh one. */ + method?: "edit" | "repost"; +} + +export interface DebugAction { + name: string; + description: string; + /** Hint for the target argument, shown by /debug list. */ + targetHint: string; + /** Builds the message the production path would send for this target. */ + build: (client: Client, payload: Payload, target: string | undefined) => Promise; + /** Sends for real through the production channel. Omit when live is unsupported. */ + live?: ( + client: Client, + payload: Payload, + target: string | undefined, + options: LiveOptions, + ) => Promise; + /** Inspects the stored bot-side state for the target. */ + inspect?: (payload: Payload, target: string | undefined) => Promise>; + /** Deletes the tracked bot message and clears its stored id. Live only. */ + remove?: (client: Client, payload: Payload, target: string | undefined) => Promise; +} + +const requireChannel = (id: string | null, envName: string): string => { + if (!id) throw new Error(`${envName} is not set.`); + return id; +}; + +interface SendableChannel { + send(options: { content?: string; embeds: EmbedBuilder[] }): Promise; +} + +const textChannel = async (client: Client, channelId: string): Promise => { + const channel = await client.channels.fetch(channelId); + if (!channel || !("send" in channel)) { + throw new Error(`Channel ${channelId} is not a text channel.`); + } + return channel as unknown as SendableChannel; +}; + +interface MessageChannel { + messages: { fetch(id: string): Promise<{ delete(): Promise }> }; +} + +const fetchTrackedMessage = async (client: Client, channelId: string, messageId: string) => { + const channel = await client.channels.fetch(channelId); + if (!channel || !("messages" in channel)) { + throw new Error(`Channel ${channelId} is not a text channel.`); + } + return (channel as unknown as MessageChannel).messages.fetch(messageId); +}; + +const resolveMission = async (payload: Payload, target: string | undefined): Promise => { + if (target?.trim()) { + const resolved = await resolveMissionByRef(payload, target.trim()); + if (resolved.error || !resolved.mission) { + throw new Error(resolved.error ?? `No mission matches "${target}".`); + } + return resolved.mission; + } + const next = await getNextUpcomingScheduledMission(payload); + if (!next) throw new Error("No upcoming Scheduled mission found. Pass a mission target."); + return next; +}; + +const parseId = (target: string | undefined, label: string): number => { + const id = Number(target?.trim()); + if (!Number.isInteger(id) || id <= 0) { + throw new Error(`Pass the ${label} ID as the target.`); + } + return id; +}; + +const loadEventLog = (payload: Payload, id: number): Promise => + payload.findByID({ + collection: "game-event-logs", + id, + depth: 0, + overrideAccess: true, + }) as Promise; + +const achievementGroupFor = async (payload: Payload, id: number) => { + const anchor = (await payload.findByID({ + collection: "achievements", + id, + depth: 1, + overrideAccess: true, + })) as unknown as AchievementAnnouncementRow; + const res = await payload.find({ + collection: "achievements", + where: { + and: [ + { window: { equals: anchor.window } }, + { windowStart: { equals: anchor.windowStart } }, + ], + }, + depth: 1, + limit: 100, + overrideAccess: true, + }); + const group = groupAchievementsForAnnouncement( + res.docs as unknown as AchievementAnnouncementRow[], + )[0]; + if (!group) { + throw new Error( + `No achievements found for window ${achievementWindowLabel(anchor.window, anchor.windowStart, anchor.windowEnd)}.`, + ); + } + return group; +}; + +const achievementEmbed = (group: Awaited>): EmbedBuilder => { + const rendered = renderAchievementAnnouncement(group); + return new EmbedBuilder() + .setTitle(rendered.title) + .setDescription(rendered.description) + .setColor(rendered.color) + .addFields(rendered.fields); +}; + +const changelogTarget = (version: string | undefined) => { + const content = readFileSync(CHANGELOG_PATH, "utf8"); + const resolved = resolveChangelog(content, version); + if (!resolved.found || resolved.messages.length === 0 || !resolved.version) { + throw new Error( + version ? `No changelog entry found for version ${version}.` : "The changelog has no entries.", + ); + } + return { version: resolved.version, messages: resolved.messages }; +}; + +export const debugActions: DebugAction[] = [ + { + name: "rollcall", + description: "Live roll-call embed with RSVP buttons", + targetHint: "mission ID, name, or code name (omit for next upcoming op)", + build: async (_client, payload, target) => { + const mission = await resolveMission(payload, target); + const message = await buildRollCallMessage(payload, mission); + return { embeds: message.embeds, components: message.components }; + }, + live: async (client, payload, target, options) => { + const mission = await resolveMission(payload, target); + if (options.method === "repost") { + const opsChannelId = requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID"); + await postEmbed(client, payload, opsChannelId, mission); + return `Posted a fresh roll-call for **${mission.name}** in the ops channel and linked it.`; + } + const result = await forceRollCall(client, payload, mission); + return result === "updated" + ? `Edited the live roll-call for **${mission.name}** in place.` + : `No live roll-call existed, so posted a fresh one for **${mission.name}**.`; + }, + inspect: async (payload, target) => { + const mission = await resolveMission(payload, target); + return { + mission: `#${mission.id} ${mission.name}`, + discordMessageId: mission.discordMessageId ?? null, + discordAttendanceSentAt: mission.discordAttendanceSentAt ?? null, + discordAttendanceHash: mission.discordAttendanceHash ? "set" : null, + discordModlistHash: mission.discordModlistHash ? "set" : null, + imminentReminderSentAt: mission.imminentReminderSentAt ?? null, + evaluationRemindersSentAt: mission.evaluationRemindersSentAt ?? null, + }; + }, + remove: async (client, payload, target) => { + const mission = await resolveMission(payload, target); + if (!mission.discordMessageId) throw new Error("No live roll-call is stored for this mission."); + const message = await fetchTrackedMessage( + client, + requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID"), + mission.discordMessageId, + ); + await message.delete(); + await payload.update({ + collection: "missions", + id: mission.id, + data: { discordMessageId: null, discordAttendanceHash: null }, + overrideAccess: true, + }); + return `Deleted the roll-call message for **${mission.name}**. The one-shot marker is kept, so it will not repost on its own.`; + }, + }, + { + name: "modlist", + description: "Modlist attachment or download-link message", + targetHint: "mission ID, name, or code name", + build: async (_client, payload, target) => { + const mission = await resolveMission(payload, target); + const modlist = await resolveModlist(payload, mission); + if (!modlist) throw new Error(`${mission.name} has no modlist attached.`); + return buildModlistMessage(payload, mission, modlist, "new"); + }, + live: async (client, payload, target) => { + const mission = await resolveMission(payload, target); + const modlist = await resolveModlist(payload, mission); + if (!modlist) throw new Error(`${mission.name} has no modlist attached.`); + const opsChannelId = requireChannel(botConfig.opsChannelId, "DISCORD_OPS_CHANNEL_ID"); + await postModlistMessage(client, payload, opsChannelId, mission, modlist, "new"); + return `Posted the modlist message for **${mission.name}**. Stored markers were not changed.`; + }, + }, + { + name: "npc-dispatch", + description: "NPC dispatch embed for a dialogue event", + targetHint: "game event log ID", + build: async (_client, payload, target) => { + const doc = await loadEventLog(payload, parseId(target, "game event log")); + return { embeds: [buildNpcEmbed(doc)] }; + }, + live: async (client, payload, target) => { + const doc = await loadEventLog(payload, parseId(target, "game event log")); + const channel = await textChannel( + client, + requireChannel(botConfig.npcEventChannelId, "DISCORD_NPC_EVENT_CHANNEL_ID"), + ); + await channel.send({ embeds: [buildNpcEmbed(doc)] }); + return `Posted a copy of NPC dispatch event #${doc.id}. Its discordAnnouncedAt stamp was not changed.`; + }, + inspect: async (payload, target) => { + const doc = await loadEventLog(payload, parseId(target, "game event log")); + return { + event: `#${doc.id}`, + discordRequested: doc.discordRequested ?? false, + discordAnnouncedAt: doc.discordAnnouncedAt ?? null, + discordMessageId: doc.discordMessageId ?? null, + }; + }, + remove: async (client, payload, target) => { + const doc = await loadEventLog(payload, parseId(target, "game event log")); + if (!doc.discordMessageId) throw new Error("No dispatch message is stored for this event."); + const message = await fetchTrackedMessage( + client, + requireChannel(botConfig.npcEventChannelId, "DISCORD_NPC_EVENT_CHANNEL_ID"), + doc.discordMessageId, + ); + await message.delete(); + await payload.update({ + collection: "game-event-logs", + id: doc.id, + data: { discordMessageId: null }, + overrideAccess: true, + depth: 0, + }); + return `Deleted the dispatch message for event #${doc.id}. discordAnnouncedAt is kept, so it will not repost.`; + }, + }, + { + name: "achievement", + description: "Minigame results embed for an award window", + targetHint: "any achievement ID in the window", + build: async (_client, payload, target) => { + const group = await achievementGroupFor(payload, parseId(target, "achievement")); + return { embeds: [achievementEmbed(group)] }; + }, + live: async (client, payload, target) => { + const group = await achievementGroupFor(payload, parseId(target, "achievement")); + const channel = await textChannel( + client, + requireChannel(botConfig.announceChannelId, "DISCORD_ANNOUNCE_CHANNEL_ID"), + ); + await channel.send({ embeds: [achievementEmbed(group)] }); + return `Posted a copy of the results for "${group.label}". announcedAt was not changed.`; + }, + }, + { + name: "imminent", + description: "Imminent-op reminder embed (live thread pings are not offered)", + targetHint: "mission ID, name, or code name", + build: async (_client, payload, target) => { + const mission = await resolveMission(payload, target); + return { embeds: [renderImminentEmbed(mission)] }; + }, + }, + { + name: "ready-reminders", + description: "Schedule-check DM to the op creator (preview only)", + targetHint: "mission ID, name, or code name", + build: async (_client, payload, target) => { + const mission = await resolveMission(payload, target); + return { embeds: [renderReadyEmbed(mission, new Date())] }; + }, + }, + { + name: "friday-notice", + description: "Friday open-slot notice for #side-ops (sandbox only; live would fool the dedup token)", + targetHint: "none", + build: async (client, _payload, _target) => { + const zeusRoleId = await resolveZeusRoleId(client); + return { content: renderNotice(zeusRoleId), embeds: [] }; + }, + }, + { + name: "changelog", + description: "Release notes for one CHANGELOG.md version (live posts to #releases)", + targetHint: "version, e.g. 0.4.0 (omit for latest)", + build: async (_client, _payload, target) => { + const { version, messages } = changelogTarget(target?.trim().replace(/^v/i, "")); + return { embeds: renderVersionEmbeds(version, messages) }; + }, + live: async (client, _payload, target) => { + const { version, messages } = changelogTarget(target?.trim().replace(/^v/i, "")); + const channelId = requireChannel( + botConfig.changelogChannelId ?? botConfig.announceChannelId, + "DISCORD_CHANGELOG_CHANNEL_ID", + ); + const channel = await client.channels.fetch(channelId); + if (!channel || !("send" in channel)) { + throw new Error(`Releases channel ${channelId} is not a text channel.`); + } + const posted = await postVersion(channel as TextBasedChannelFields, version, messages); + return `Posted **Changelog v${version}** to the releases channel (${posted} message(s)).`; + }, + }, + { + name: "evaluations", + description: "Evaluation reminder DM (preview only; shows first recipient)", + targetHint: "mission ID, name, or code name", + build: async (_client, payload, target) => { + const mission = await resolveMission(payload, target); + const plan = await computeEvaluationReminderPlan(payload, mission.id); + const recipients = plan.recipients.filter((r) => r.discordId); + const first = recipients[0]; + if (!first) throw new Error("No recipients with a linked Discord account."); + return { + content: `${recipients.length} recipient(s) would be DMed. Showing the first (user #${first.userId}).`, + embeds: [ + renderEvaluationEmbed(mission, first.rateLeaders, first.rateSubordinates, botConfig.appUrl), + ], + }; + }, + }, + { + name: "notification", + description: "Notification bridge DM (preview only)", + targetHint: "user-notification ID", + build: async (_client, payload, target) => { + const doc = (await payload.findByID({ + collection: "user-notifications", + id: parseId(target, "user-notification"), + depth: 0, + overrideAccess: true, + })) as unknown as UserNotification; + return { embeds: [renderNotificationEmbed(doc)] }; + }, + }, + { + name: "transfer", + description: "Transfer approval request DM (preview only)", + targetHint: "assignment-transfer request ID", + build: async (_client, payload, target) => { + const doc = (await payload.findByID({ + collection: "assignment-transfers", + id: parseId(target, "transfer request"), + depth: 0, + overrideAccess: true, + })) as unknown as AssignmentTransfer; + return { + embeds: [requestEmbed(await contextFor(payload, doc))], + components: [transferDecisionRow(doc.id)], + }; + }, + }, +]; + +export const findDebugAction = (name: string): DebugAction | undefined => + debugActions.find((action) => action.name === name);