1
0
Fork 0

fix(bot): show the Friday op slot date in Eastern time

Discord renders <t:epoch:D> in each viewer's timezone, so the slot's Friday
00:00 Eastern epoch read as Thursday for members west of Eastern. Render the
date as a pinned Eastern label instead.

- add fridayDateLabel(): the upcoming Friday in America/New_York
- noticeToken() now returns that label, keeping dedup stable per Friday
- legacyNoticeToken() still matches older <t:epoch:D> notices and the service
  rewrites them in place, so a deploy does not duplicate or leave one behind
- only match the bot's own messages, since a plain-date token could otherwise
  hit a member's message (which the bot cannot edit)
- document the timezone rule in the bot AGENTS.md
This commit is contained in:
Jason Fraley 2026-11-20 17:25:04 -05:00
parent 9288d1498e
commit 4fba0b03c7
4 changed files with 95 additions and 19 deletions

View file

@ -99,7 +99,7 @@ Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start
## Feature flow: Friday open-slot notice ## Feature flow: Friday open-slot notice
At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 **America/New_York** computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by \<user\>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday `<t:epoch:D>` token and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Drafts (Concept) count as the slot being taken. At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 **America/New_York** computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by \<user\>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday Eastern date label (e.g. `January 15, 2027`) and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Never use Discord's `<t:epoch:D>` for this date: it renders in each viewer's timezone, so an epoch at Friday 00:00 Eastern displayed as Thursday for members in Central/Mountain/Pacific/Hawaii. Notices still carrying the old `<t:epoch:D>` token are matched and rewritten in place to the Eastern label. Drafts (Concept) count as the slot being taken.
## Feature flow: assignment transfers ## Feature flow: assignment transfers

View file

@ -1,13 +1,19 @@
import { type Client, type Collection, type Message, type TextBasedChannelFields } from "discord.js"; import {
type Client,
type Collection,
type Message,
type TextBasedChannelFields,
} from "discord.js";
import type { Payload } from "payload"; import type { Payload } from "payload";
import { botConfig } from "@/bot/config"; import { botConfig } from "@/bot/config";
import { import {
SIDE_OPS_NOTICE_ROLE_NAME, SIDE_OPS_NOTICE_ROLE_NAME,
fridayDateLabel,
getFridayClaimant, getFridayClaimant,
hasMissionOnFriday, hasMissionOnFriday,
isNoticeDue, isNoticeDue,
legacyNoticeToken,
noticeToken, noticeToken,
upcomingFridayRange,
} from "@/lib/intelligence/fridayOpsNotice"; } from "@/lib/intelligence/fridayOpsNotice";
/** /**
@ -18,7 +24,7 @@ import {
* When a non-superuser (a community zeus) later claims the slot, the notice * When a non-superuser (a community zeus) later claims the slot, the notice
* is edited to credit them instead; if that claim op is later cancelled (or * is edited to credit them instead; if that claim op is later cancelled (or
* deleted), the notice reverts to the open-slot state. Dedup needs no DB * deleted), the notice reverts to the open-slot state. Dedup needs no DB
* state: the notice embeds a stable per-Friday timestamp token and the * state: the notice embeds a stable per-Friday Eastern date label and the
* service scans recent channel messages for it (and for the claim line) * service scans recent channel messages for it (and for the claim line)
* before posting or editing, so bot restarts never double-post or re-credit. * before posting or editing, so bot restarts never double-post or re-credit.
*/ */
@ -55,9 +61,8 @@ export const resolveZeusRoleId = async (client: Client): Promise<string | null>
export const renderNotice = (zeusRoleId: string | null, now = new Date()): string => { export const renderNotice = (zeusRoleId: string | null, now = new Date()): string => {
const mention = zeusRoleId ? `<@&${zeusRoleId}> ` : ""; const mention = zeusRoleId ? `<@&${zeusRoleId}> ` : "";
const { epoch } = upcomingFridayRange(now);
return ( return (
`${mention}The Friday op slot (<t:${epoch}:D>) is still open, and you are welcome to host an op: ` + `${mention}The Friday op slot (${fridayDateLabel(now)}) is still open, and you are welcome to host an op: ` +
`schedule one via the Friday Ops calendar at ${botConfig.appUrl}/intelligence/missions/calendar. ` + `schedule one via the Friday Ops calendar at ${botConfig.appUrl}/intelligence/missions/calendar. ` +
"If nobody picks it up, the slot will either stay empty (no op that Friday) or Jason will host it himself." "If nobody picks it up, the slot will either stay empty (no op that Friday) or Jason will host it himself."
); );
@ -70,12 +75,25 @@ const CLAIM_LINE_PATTERN =
const creditedNameOf = (content: string): string | null => const creditedNameOf = (content: string): string | null =>
content.match(CLAIM_LINE_PATTERN)?.[1] ?? null; content.match(CLAIM_LINE_PATTERN)?.[1] ?? null;
/**
* The notice is found by content token, and only among the bot's own messages:
* the token is a plain date now, so a member typing the same date in the
* channel must not be mistaken for the notice (the bot cannot edit it anyway).
*/
export const findNoticeMessage = async ( export const findNoticeMessage = async (
channel: SideOpsChannel, channel: SideOpsChannel,
token: string, tokens: string | string[],
botUserId?: string,
): Promise<Message | null> => { ): Promise<Message | null> => {
const wanted = Array.isArray(tokens) ? tokens : [tokens];
const recent = await channel.messages.fetch({ limit: MESSAGE_SCAN_LIMIT }); const recent = await channel.messages.fetch({ limit: MESSAGE_SCAN_LIMIT });
return recent.find((message) => message.content.includes(token)) ?? null; return (
recent.find(
(message) =>
(botUserId == null || message.author.id === botUserId) &&
wanted.some((token) => message.content.includes(token)),
) ?? null
);
}; };
const processNotice = async ( const processNotice = async (
@ -90,7 +108,8 @@ const processNotice = async (
const channel = await getSideOpsChannel(client, channelId); const channel = await getSideOpsChannel(client, channelId);
const token = noticeToken(now); const token = noticeToken(now);
const notice = await findNoticeMessage(channel, token); const legacyToken = legacyNoticeToken(now);
const notice = await findNoticeMessage(channel, [token, legacyToken], client.user?.id);
if (!notice) { if (!notice) {
const slotTaken = claim != null || (await hasMissionOnFriday(payload, now)); const slotTaken = claim != null || (await hasMissionOnFriday(payload, now));
@ -109,18 +128,32 @@ const processNotice = async (
return "posted"; return "posted";
} }
const credited = creditedNameOf(notice.content); // A notice posted before the Eastern label existed still carries the old
// `<t:epoch:D>` token (which reads as Thursday west of Eastern). Upgrade it
// in place so the visible date is correct for everyone.
let content = notice.content;
if (!content.includes(token) && content.includes(legacyToken)) {
content = content.replace(legacyToken, token);
await notice.edit(content);
payload.logger.info(
`[Bot] Friday open-slot notice for ${token}: upgraded the legacy date token to the Eastern label.`,
);
}
const credited = creditedNameOf(content);
if (!claim) { if (!claim) {
if (!credited) return "idle"; if (!credited) return "idle";
await notice.edit(notice.content.replace(CLAIM_LINE_PATTERN, "")); await notice.edit(content.replace(CLAIM_LINE_PATTERN, ""));
payload.logger.info( payload.logger.info(
`[Bot] Friday open-slot notice for ${token}: claim by ${credited} was cancelled; notice reverted to the open-slot state.`, `[Bot] Friday open-slot notice for ${token}: claim by ${credited} was cancelled; notice reverted to the open-slot state.`,
); );
return "edited"; return "edited";
} }
if (credited !== claim.userName) { if (credited !== claim.userName) {
const base = credited ? notice.content.replace(CLAIM_LINE_PATTERN, "") : notice.content; const base = credited ? content.replace(CLAIM_LINE_PATTERN, "") : content;
await notice.edit(`${base}\n\n${CLAIM_MARKER} ${claim.userName}. Thank you for hosting for our community!`); await notice.edit(
`${base}\n\n${CLAIM_MARKER} ${claim.userName}. Thank you for hosting for our community!`,
);
payload.logger.info( payload.logger.info(
`[Bot] Friday open-slot notice for ${token} claimed by ${claim.userName}; notice updated.`, `[Bot] Friday open-slot notice for ${token} claimed by ${claim.userName}; notice updated.`,
); );

View file

@ -120,7 +120,8 @@ const etMidnightUtc = (year: number, month: number, day: number): number => {
* evening Eastern once fell outside the old server-local window). When `now` * evening Eastern once fell outside the old server-local window). When `now`
* is already Friday Eastern, that day itself is the slot, keeping the dedup * is already Friday Eastern, that day itself is the slot, keeping the dedup
* token stable from Wednesday through the op day so late claims still credit. * token stable from Wednesday through the op day so late claims still credit.
* Used both for the mission-existence query and for the per-Friday token. * Used for the mission-existence query, the per-Friday notice token, and the
* legacy `<t:epoch:D>` token still recognized from older notices.
*/ */
export const upcomingFridayRange = (now: Date): { start: Date; end: Date; epoch: number } => { export const upcomingFridayRange = (now: Date): { start: Date; end: Date; epoch: number } => {
const et = etDate(now); const et = etDate(now);
@ -204,8 +205,30 @@ export const getFridayClaimant = async (
}; };
/** /**
* Stable per-Friday token embedded in the notice message (renders as the * The upcoming Friday's calendar date as seen in America/New_York, e.g.
* Friday's date) so the bot can detect an existing notice by scanning recent * "January 15, 2027". Discord's `<t:epoch:D>` markup renders in the VIEWER's
* channel messages, surviving restarts without any DB state. * timezone, so an epoch at Friday 00:00 Eastern showed up as Thursday for
* members in Central, Mountain, Pacific, and Hawaii time; a pinned Eastern
* label reads the same for everyone.
*/ */
export const noticeToken = (now: Date): string => `<t:${upcomingFridayRange(now).epoch}:D>`; export const fridayDateLabel = (now: Date): string =>
new Intl.DateTimeFormat("en-US", {
timeZone: ET_TIME_ZONE,
month: "long",
day: "numeric",
year: "numeric",
}).format(upcomingFridayRange(now).start);
/**
* Stable per-Friday token embedded in the notice message (the Eastern date
* label) so the bot can detect an existing notice by scanning recent channel
* messages, surviving restarts without any DB state.
*/
export const noticeToken = (now: Date): string => fridayDateLabel(now);
/**
* The `<t:epoch:D>` token older builds embedded. Kept so a notice posted by
* the previous build on a deploy evening is still recognized instead of
* re-posted as a duplicate for the same Friday.
*/
export const legacyNoticeToken = (now: Date): string => `<t:${upcomingFridayRange(now).epoch}:D>`;

View file

@ -4,9 +4,11 @@ import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types"; import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import { import {
fridayDateLabel,
getFridayClaimant, getFridayClaimant,
hasMissionOnFriday, hasMissionOnFriday,
isNoticeDue, isNoticeDue,
legacyNoticeToken,
noticeToken, noticeToken,
upcomingFridayRange, upcomingFridayRange,
} from "@/lib/intelligence/fridayOpsNotice"; } from "@/lib/intelligence/fridayOpsNotice";
@ -256,15 +258,33 @@ describe("Friday open-slot notice", () => {
expect(upcomingFridayRange(SATURDAY).start.toISOString()).toBe("2027-01-22T05:00:00.000Z"); expect(upcomingFridayRange(SATURDAY).start.toISOString()).toBe("2027-01-22T05:00:00.000Z");
}); });
it("labels the upcoming Friday in Eastern time so every viewer sees the same day", () => {
// The slot instant is Friday 00:00 Eastern. Rendered as Discord's
// `<t:epoch:D>` that reads as Thursday for viewers west of Eastern, so the
// notice carries a pinned Eastern label instead.
expect(fridayDateLabel(WEDNESDAY)).toBe("January 15, 2027");
expect(fridayDateLabel(WEDNESDAY_EVENING)).toBe("January 15, 2027");
expect(fridayDateLabel(FRIDAY)).toBe("January 15, 2027");
expect(fridayDateLabel(SATURDAY)).toBe("January 22, 2027");
});
it("builds a stable per-Friday dedup token", () => { it("builds a stable per-Friday dedup token", () => {
expect(noticeToken(WEDNESDAY)).toBe(noticeToken(TUESDAY)); expect(noticeToken(WEDNESDAY)).toBe(noticeToken(TUESDAY));
expect(noticeToken(WEDNESDAY)).toBe(`<t:${upcomingFridayRange(WEDNESDAY).epoch}:D>`); expect(noticeToken(WEDNESDAY)).toBe(fridayDateLabel(WEDNESDAY));
expect(noticeToken(WEDNESDAY)).not.toContain("<t:");
// Stable through the op day, so claims made after Thursday ET midnight // Stable through the op day, so claims made after Thursday ET midnight
// still match the notice posted on Wednesday. // still match the notice posted on Wednesday.
expect(noticeToken(FRIDAY)).toBe(noticeToken(WEDNESDAY)); expect(noticeToken(FRIDAY)).toBe(noticeToken(WEDNESDAY));
expect(noticeToken(SATURDAY)).not.toBe(noticeToken(WEDNESDAY)); expect(noticeToken(SATURDAY)).not.toBe(noticeToken(WEDNESDAY));
}); });
it("keeps recognizing the legacy Discord timestamp token", () => {
// Notices posted by older builds embed `<t:epoch:D>`; the service still
// matches it (and rewrites it to the Eastern label) instead of reposting.
expect(legacyNoticeToken(WEDNESDAY)).toBe(`<t:${upcomingFridayRange(WEDNESDAY).epoch}:D>`);
expect(legacyNoticeToken(WEDNESDAY)).toBe(legacyNoticeToken(FRIDAY));
});
it("treats the Friday slot as open only when a non-cancelled mission starts that Friday", async () => { it("treats the Friday slot as open only when a non-cancelled mission starts that Friday", async () => {
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(false); await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(false);