projects/backend/convex/recovery.ts

import { v } from "convex/values"
import { query, type QueryCtx } from "./_generated/server.js"
import type { Doc } from "./_generated/dataModel.js"
import {
    RECOVERY_LIMIT,
    RecoveryListRequest,
    type RecoveryEntry,
    type RecoveryInbox,
    type RecoverySource,
    type SetupProblem,
} from "@neonflux/contracts/setup"
import { serviceQuery } from "./serviceGuard.ts"
import { dashboardSession } from "./dashboard.ts"
import { readSetupSections } from "./setupCheck.ts"
import { config as moderationConfig, readSettings as readModeration } from "./moderationStore.ts"
import { readHelpDesk } from "./helpDesk.ts"
import { TEMPORARY_ROLE_KEY } from "./temporaryRolesStore.ts"
import { ONBOARDING_ROLE_KEY } from "./onboardingDomain.ts"
import { decode } from "./validation.ts"
import { youtubeSource, youtubeSubscriptions } from "./youtubeStore.ts"
import { twitchSource, twitchSubscriptions } from "./twitchStore.ts"
import { lockdownChannelsIn, readLockdown } from "./lockdownStore.ts"
import { readJailSettings } from "./jailStore.ts"
import { JAIL_RECORD_LIMIT } from "@neonflux/contracts/jail"
import { RIGHTS_SUSPENDED_COUNT_LIMIT } from "@neonflux/contracts/rights"
import { feedDelivery, feedSource, feedSubscriptions } from "./feedStore.ts"
import { feedProviderNames } from "@neonflux/contracts/feeds"
import { readCounters } from "./countersStore.ts"
import { counterCountProblemText } from "@neonflux/contracts/counters"
import { giveawayRow } from "./giveawaysStore.ts"
import { readBoards } from "./boardsStore.ts"

// The recovery inbox: failed, stuck or uncertain work that a feature already records, the features that are on but cannot act and the
// problems of the latest permission check. It adds no tracking of its own. Each source reads at most RECOVERY_SCAN rows through its
// own index and shows its newest RECOVERY_PER_SOURCE entries, and the inbox shows at most RECOVERY_LIMIT entries. Stopped role
// removals continue past their newest RECOVERY_PER_SOURCE in pages, so every one of them can be listed
export const RECOVERY_SCAN = 50
export const RECOVERY_PER_SOURCE = 10
/** Failures that nothing can resolve anymore stay in the inbox this long, so it shows what needs attention now */
export const RECOVERY_SETTLED_MS = 7 * 86400000
// A jail this long past its end is one its release could not run
const JAIL_RELEASE_LATE_MS = 5 * 60000

type Work = Extract<RecoveryEntry, { kind: "work" }>
const work = (source: RecoverySource, summary: string, next: string, at?: number): Work => ({
    kind: "work",
    source,
    ...(at !== undefined ? { at } : {}),
    summary,
    next,
})
const newest = <T>(rows: T[], at: (row: T) => number) =>
    rows.sort((a, b) => at(b) - at(a)).slice(0, RECOVERY_PER_SOURCE)
const retried = "NeonFlux tries again every 10 minutes"
// Members, roles and channels are mention markup, which chat shows as names and the website's recovery inbox shows the same way.
// Commands name a member by mention and a panel by name, so staff type them as chat shows them
const member = (id: string) => `<@${id}>`,
    role = (id: string) => `<@&${id}>`,
    channel = (id: string) => `<#${id}>`

// Posts of every feature go through the publisher, whose attempts keep an unknown outcome open until it is reconciled or resolved
async function publishingEntry(ctx: QueryCtx, attempt: Doc<"publishingAttempts">): Promise<Work> {
    const consumer = attempt.consumer,
        post = attempt.postNo,
        unknown = attempt.outcome === "uncertain",
        subject = consumer ? `Post #${post}` : "It"
    // A send to a forum or media channel creates a forum post, whose thread is known once Fluxer answered
    const done = `${attempt.action === "send" ? "sent" : "edited"}${attempt.threadId ? ` in the forum post ${channel(attempt.threadId)}` : ` in channel ${channel(attempt.channelId)}`}`
    const outcome = unknown
        ? `NeonFlux could not confirm whether ${subject.toLowerCase()} was ${done}`
        : `${subject} could not be ${done}, and nothing changed`
    if (!consumer)
        return work(
            "publishing",
            `Post #${post}: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed`
                : `!publish status ${post}, then send or edit it again`,
            attempt.createdAt,
        )
    if (consumer.type === "schedule") {
        // Schedule commands name the schedule, so its row is read once by number. A forgotten schedule has nothing left to recheck
        const schedule = await ctx.db
            .query("schedules")
            .withIndex("by_number", (q) => q.eq("serverId", attempt.serverId).eq("scheduleNo", consumer.scheduleNo))
            .unique()
        return work(
            "schedules",
            `Schedule ${schedule?.name ?? `#${consumer.scheduleNo}`}, date ${consumer.occurrenceNo}: ${outcome}`,
            !schedule
                ? "The schedule was forgotten, so NeonFlux cannot recheck the post. Check the channel in Fluxer if it matters"
                : unknown
                  ? `!publish schedule reconcile ${schedule.name} ${post}`
                  : `!publish schedule status ${schedule.name}`,
            attempt.createdAt,
        )
    }
    if (consumer.type === "event") {
        // Event commands name the event, so its row is read once by number. A forgotten event has nothing left to recheck
        const event = await ctx.db
            .query("events")
            .withIndex("by_number", (q) => q.eq("serverId", attempt.serverId).eq("eventNo", consumer.eventNo))
            .unique()
        return work(
            "events",
            `${consumer.purpose === "card" ? "Card" : "Reminder"} of event ${event?.name ?? `#${consumer.eventNo}`}: ${outcome}`,
            !event
                ? "The event was forgotten, so NeonFlux cannot recheck the post. Check the channel in Fluxer if it matters"
                : unknown
                  ? `!event reconcile ${event.name} ${post}`
                  : `!event status ${event.name}`,
            attempt.createdAt,
        )
    }
    if (consumer.type === "milestone")
        return work(
            "milestones",
            `${consumer.kind === "birthday" ? "Birthday" : "Anniversary"} post for ${member(consumer.userId)}: ${outcome}`,
            unknown ? `!milestone reconcile ${consumer.kind} ${post}` : `!milestone status ${consumer.kind}`,
            attempt.createdAt,
        )
    if (consumer.type === "youtube") {
        // The alert names its video by title, read once from the server's own delivery row
        const delivery = await ctx.db
            .query("youtubeDeliveries")
            .withIndex("by_video", (q) =>
                q
                    .eq("serverId", attempt.serverId)
                    .eq("youtubeChannelId", consumer.youtubeChannelId)
                    .eq("videoId", consumer.videoId),
            )
            .first()
        return work(
            "youtube",
            `YouTube alert for ${delivery ? `the video ${delivery.title}` : "a new video"}: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed. NeonFlux never posts an alert twice`
                : "!youtube status shows the channel's alerts",
            attempt.createdAt,
        )
    }
    if (consumer.type === "board") {
        // A count update that failed is corrected by a later one, so only a post's unknown outcome needs staff
        return work(
            "boards",
            `A board post: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed. NeonFlux never posts a message on a board twice`
                : "!board list shows the boards",
            attempt.createdAt,
        )
    }
    if (consumer.type === "feed") {
        // The post names itself by its opening words, read once from the server's own delivery row
        const delivery = await feedDelivery(
            ctx,
            attempt.serverId,
            consumer.provider,
            consumer.accountId,
            consumer.itemId,
        )
        return work(
            "feeds",
            `${feedProviderNames[consumer.provider]} post ${delivery ? delivery.title : "from a followed account"}: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed. NeonFlux never posts a feed post twice`
                : "!feed status shows the followed accounts",
            attempt.createdAt,
        )
    }
    if (consumer.type === "giveaway") {
        const row = await giveawayRow(ctx, attempt.serverId, consumer.giveawayNo)
        return work(
            "giveaways",
            `Card of giveaway #${consumer.giveawayNo}${row ? ` for ${row.prize}` : ""}: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed. NeonFlux never posts a card twice`
                : `!giveaway show ${consumer.giveawayNo}`,
            attempt.createdAt,
        )
    }
    if (consumer.type === "twitch") {
        // The alert names its stream by title, read once from the server's own delivery row
        const delivery = await ctx.db
            .query("twitchDeliveries")
            .withIndex("by_stream", (q) =>
                q
                    .eq("serverId", attempt.serverId)
                    .eq("twitchChannelId", consumer.twitchChannelId)
                    .eq("streamId", consumer.streamId),
            )
            .first()
        return work(
            "twitch",
            `Twitch alert for ${delivery ? `the stream ${delivery.title}` : "a new stream"}: ${outcome}`,
            unknown
                ? `!publish reconcile ${post}, or record what happened with !publish resolve ${post} sent <message-id> or !publish resolve ${post} failed. NeonFlux never posts an alert twice`
                : "!twitch status shows the channel's alerts",
            attempt.createdAt,
        )
    }
    return work(
        "suggestions",
        `Card of suggestion #${consumer.suggestionNo}: ${outcome}`,
        `!suggest publication ${consumer.suggestionNo}, then !suggest reconcile ${consumer.suggestionNo}`,
        attempt.createdAt,
    )
}

async function readPublishing(ctx: QueryCtx, serverId: string, now: number) {
    const unknown = await ctx.db
        .query("publishingAttempts")
        .withIndex("by_pending", (q) => q.eq("serverId", serverId).eq("outcome", "uncertain"))
        .order("desc")
        .take(RECOVERY_SCAN)
    const failed = await ctx.db
        .query("publishingAttempts")
        .withIndex("by_pending", (q) =>
            q
                .eq("serverId", serverId)
                .eq("outcome", "failed")
                .gt("createdAt", now - RECOVERY_SETTLED_MS),
        )
        .order("desc")
        .take(RECOVERY_SCAN)
    // A failed count update needs nothing from staff, since the next change corrects the card
    const settled = failed.filter((attempt) => attempt.consumer?.type !== "board" || attempt.action !== "edit")
    return Promise.all(
        newest([...unknown.filter((attempt) => attempt.unresolved), ...settled], (attempt) => attempt.createdAt).map(
            (attempt) => publishingEntry(ctx, attempt),
        ),
    )
}

async function readRoles(ctx: QueryCtx, serverId: string) {
    const attempts = (
        await ctx.db
            .query("roleAttempts")
            .withIndex("by_server_pending", (q) => q.eq("serverId", serverId).eq("outcome", "uncertain"))
            .order("desc")
            .take(RECOVERY_SCAN)
    ).filter((attempt) => attempt.observationAt === undefined)
    const entries: Work[] = []
    for (const attempt of newest(attempts, (attempt) => attempt.createdAt)) {
        const key = attempt.consumerKey,
            user = attempt.userId,
            panel = /^panel:(.+):\d+$/.exec(key)?.[1]
        const kind = panel
            ? (
                  await ctx.db
                      .query("rolePanels")
                      .withIndex("by_server_name", (q) => q.eq("serverId", serverId).eq("name", panel))
                      .unique()
              )?.kind
            : undefined
        const who = member(user),
            next = panel
                ? kind === "verification"
                    ? `!verify reconcile ${who}`
                    : `!roles reconcile ${panel} ${who}`
                : key.startsWith("autorole:")
                  ? `!autorole reconcile ${who}`
                  : key === TEMPORARY_ROLE_KEY
                    ? `!temprole reconcile ${who}`
                    : key === "level"
                      ? `!level reconcile ${who}`
                      : key === ONBOARDING_ROLE_KEY
                        ? "NeonFlux never repeats the completion role. Check the member's roles in Fluxer and give the role by hand if it is missing"
                        : `!rolepicker reconcile ${who}`
        entries.push(
            work(
                "roles",
                `${member(user)}: NeonFlux could not confirm whether it ${attempt.action === "add" ? "gave" : "removed"} ${role(attempt.roleId)}`,
                next,
                attempt.createdAt,
            ),
        )
    }
    return entries
}

// Role removals that stopped at a change that needs a check, newest first by when each started, 10 at a time. before continues the list
async function readRemovals(ctx: QueryCtx, serverId: string, before?: number) {
    const rows = await ctx.db
        .query("roleWithdrawals")
        .withIndex("by_server_status", (q) =>
            before === undefined
                ? q.eq("serverId", serverId).eq("status", "blocked")
                : q.eq("serverId", serverId).eq("status", "blocked").lt("createdAt", before),
        )
        .order("desc")
        .take(RECOVERY_PER_SOURCE + 1)
    const shown = rows.slice(0, RECOVERY_PER_SOURCE),
        entries: Work[] = []
    for (const row of shown) {
        const panel = /^panel:(.+):\d+$/.exec(row.consumerKey)?.[1]
        const kind = panel
            ? (
                  await ctx.db
                      .query("rolePanels")
                      .withIndex("by_server_name", (q) => q.eq("serverId", serverId).eq("name", panel))
                      .unique()
              )?.kind
            : undefined
        // Autorole and the rules panel continue their newest removal, and a reaction panel is named. A stopped deletion
        // is finished by deleting again, since only its last revision's withdrawal carries the deletion
        const command = !panel
            ? "!autorole next"
            : kind === "verification"
              ? "!verify next"
              : `!roles next ${panel}, or !roles delete ${panel} to finish a deletion`
        entries.push(
            work(
                "removals",
                `${panel ? `Panel ${panel}` : "Autorole"}: Taking back its roles stopped at a role change that needs a check`,
                `Continue with ${command}`,
                row.createdAt,
            ),
        )
    }
    return { entries, ...(rows.length > shown.length ? { next: shown.at(-1)!.createdAt } : {}) }
}

const temporaryProblems: Record<
    Exclude<NonNullable<Doc<"temporaryRoleGrants">["problem"]>, "waiting">,
    [string, string]
> = {
    permission: ["NeonFlux lacks Manage roles", `Grant Manage roles to the NeonFlux role. ${retried}`],
    role: ["the role ranks at or above NeonFlux's highest role", `Move the NeonFlux role above the role. ${retried}`],
    refused: ["Fluxer refused the change", `!health names missing permissions. ${retried}`],
    unavailable: ["Fluxer could not be read", retried],
    uncertain: ["NeonFlux could not confirm the last role change", ""],
}
async function readTemporaryRoles(ctx: QueryCtx, serverId: string, now: number) {
    const grants = (
        await ctx.db
            .query("temporaryRoleGrants")
            .withIndex("by_server_due", (q) => q.eq("serverId", serverId))
            .take(RECOVERY_SCAN)
    )
        // A grant waiting for its member needs no staff step, since NeonFlux tries again until it ends
        .filter((grant) => grant.problem !== undefined && grant.problem !== "waiting")
    // A removal problem dates from the end time, and an unconfirmed grant or renewal from its last change
    const at = (grant: Doc<"temporaryRoleGrants">) => (grant.endsAt <= now ? grant.endsAt : grant.updatedAt)
    return newest(grants, at).map((grant) => {
        const [why, next] = temporaryProblems[grant.problem as keyof typeof temporaryProblems]
        return work(
            "temproles",
            `Temporary role ${role(grant.roleId)} of ${member(grant.userId)}: ${why}`,
            next || `!temprole reconcile ${member(grant.userId)}`,
            at(grant),
        )
    })
}

async function readTickets(ctx: QueryCtx, serverId: string) {
    const tickets = (
        await ctx.db
            .query("tickets")
            .withIndex("by_number", (q) => q.eq("serverId", serverId))
            .order("desc")
            .take(RECOVERY_SCAN)
    )
        .filter((ticket) => ticket.state === "uncertain")
        .slice(0, RECOVERY_PER_SOURCE)
    const entries: Work[] = []
    for (const ticket of tickets) {
        const attempt = ticket.currentAttemptId ? await ctx.db.get(ticket.currentAttemptId) : null
        entries.push(
            work(
                "tickets",
                `Ticket #${ticket.ticketNo}: NeonFlux could not confirm whether ${!ticket.transition ? "its channel was created" : `it was ${ticket.transition === "close" ? "closed" : "reopened"}`}`,
                `!ticket reconcile ${ticket.ticketNo}${ticket.channelId ? "" : `, or !ticket abandon ${ticket.ticketNo} if no channel was created`}`,
                attempt?.createdAt ?? ticket.createdAt,
            ),
        )
    }
    return entries
}

// Why the cleanup worker stopped in a channel, in plain words instead of the stage it records
const cleanupStops: Partial<Record<string, string>> = {
    authority: "NeonFlux could not confirm its permissions there",
    history: "NeonFlux could not read the channel's messages",
    malformed: "NeonFlux could not save the messages it read",
    target: "A message could not be deleted",
}
async function readCleanup(ctx: QueryCtx, serverId: string, now: number) {
    // A claimed deletion that failed or has no known result, for a week like other settled failures
    const targets = newest(
        (
            await Promise.all(
                (["failed", "uncertain"] as const).map((state) =>
                    ctx.db
                        .query("cleanupTargets")
                        .withIndex("by_recovery_unresolved", (q) =>
                            q
                                .eq("serverId", serverId)
                                .eq("state", state)
                                .eq("replayBlocked", true)
                                .gt("updatedAt", now - RECOVERY_SETTLED_MS),
                        )
                        .order("desc")
                        .take(RECOVERY_PER_SOURCE),
                ),
            )
        ).flat(),
        (target) => target.updatedAt,
    )
    const entries = targets.map((target) =>
        work(
            "cleanup",
            `Cleanup in ${channel(target.channelId)}: ${target.state === "failed" ? "A message could not be deleted" : "NeonFlux could not confirm whether a message was deleted"}`,
            `!cleanup status ${channel(target.channelId)} messages shows it. NeonFlux never repeats a deletion, so check the message yourself`,
            target.updatedAt,
        ),
    )
    // Only stopped policies have a reason, so a server with hundreds of cleanup channels reads just those
    const policies = await ctx.db
        .query("cleanupPolicies")
        .withIndex("by_blocked", (q) => q.eq("serverId", serverId).eq("enabled", true).gt("blockedReason", ""))
        .take(RECOVERY_PER_SOURCE)
    // A blocked policy is current state and comes before the deletions, which are newest first
    return [
        ...policies.map((policy) =>
            work(
                "cleanup",
                `Cleanup in ${channel(policy.channelId)} stopped: ${cleanupStops[policy.blockedReason!] ?? "Something went wrong"}`,
                "Give NeonFlux View channel, Read message history and Manage messages in that channel. It checks again on its own",
            ),
        ),
        ...entries,
    ].slice(0, RECOVERY_PER_SOURCE)
}

const greetingNames = { welcome: "Welcome greeting", dm: "DM greeting", goodbye: "Goodbye greeting" } as const
const greetingCommands = { welcome: "!welcome", dm: "!welcome dm", goodbye: "!goodbye" } as const
const greetingReasons: Record<NonNullable<Doc<"greetingDeliveries">["reason"]>, string> = {
    verification: "the member did not verify",
    eligibility: "the member could not get it",
    configuration: "the greeting settings changed",
    membership: "the member left or rejoined",
    lifetime: "it waited too long",
}
async function readGreetings(ctx: QueryCtx, serverId: string, now: number) {
    const rows = (
        await ctx.db
            .query("greetingDeliveries")
            .withIndex("by_server", (q) => q.eq("serverId", serverId))
            .order("desc")
            .take(RECOVERY_SCAN)
    ).filter(
        (row) => row.state === "uncertain" || (row.state === "failed" && row.createdAt > now - RECOVERY_SETTLED_MS),
    )
    return newest(rows, (row) => row.createdAt).map((row) =>
        work(
            "greetings",
            `${greetingNames[row.route]} #${row.deliveryNo} for ${member(row.userId)}: ${
                row.state === "failed"
                    ? `Not sent${row.reason ? ` because ${greetingReasons[row.reason]}` : ""}`
                    : "NeonFlux could not confirm whether it was sent"
            }`,
            `${greetingCommands[row.route]} status ${row.deliveryNo}. NeonFlux never sends a greeting twice`,
            row.finishedAt ?? row.createdAt,
        ),
    )
}

async function readBlockedDeliveries(ctx: QueryCtx, serverId: string) {
    const permissions =
        "Give NeonFlux View channel, Send messages and Embed links in that channel. It tries again on its own"
    const schedules = (
        await ctx.db
            .query("scheduleDeliveries")
            .withIndex("by_discovery", (q) => q.eq("serverId", serverId).eq("active", true))
            .take(RECOVERY_SCAN)
    ).filter((row) => row.state === "blocked")
    const milestones: Doc<"milestoneDeliveries">[] = []
    for (const kind of ["birthday", "anniversary"] as const)
        milestones.push(
            ...(
                await ctx.db
                    .query("milestoneDeliveries")
                    .withIndex("by_route", (q) => q.eq("serverId", serverId).eq("kind", kind))
                    .order("desc")
                    .take(RECOVERY_SCAN / 2)
            ).filter((row) => row.active && row.state === "blocked"),
        )
    // Schedule commands name the schedule, so each entry reads its schedule's row once by number
    const scheduleName = async (scheduleNo: number) =>
        (
            await ctx.db
                .query("schedules")
                .withIndex("by_number", (q) => q.eq("serverId", serverId).eq("scheduleNo", scheduleNo))
                .unique()
        )?.name ?? `#${scheduleNo}`
    return [
        ...(await Promise.all(
            newest(schedules, (row) => row.dueAt).map(async (row) =>
                work(
                    "schedules",
                    `Schedule ${await scheduleName(row.scheduleNo)}, date ${row.occurrenceNo} is waiting: NeonFlux cannot post in ${channel(row.channelId)}`,
                    permissions,
                    row.dueAt,
                ),
            ),
        )),
        ...newest(milestones, (row) => row.dueAt).map((row) =>
            work(
                "milestones",
                `${row.kind === "birthday" ? "Birthday" : "Anniversary"} post for ${member(row.userId)} is waiting: NeonFlux cannot post in ${channel(row.channelId)}`,
                permissions,
                row.dueAt,
            ),
        ),
    ]
}

// Followed channels NeonFlux turned off, with the fix, and channels whose subscription at YouTube's hub keeps failing
async function readYoutube(ctx: QueryCtx, serverId: string) {
    const entries: Work[] = []
    for (const row of await youtubeSubscriptions(ctx, serverId)) {
        const source = await youtubeSource(ctx, row.youtubeChannelId),
            name = source?.title ?? row.youtubeChannelId,
            hubError = source?.lastError
        // YouTube commands take a followed channel's name, so the steps name it as entries do
        const again = `then turn the alerts back on with !youtube add ${name} #channel`
        if (row.problem === "channel")
            entries.push(
                work(
                    "youtube",
                    `YouTube alerts for ${name} are off: Their channel ${channel(row.channelId)} is gone or cannot hold alerts`,
                    `Choose a text, announcement or forum channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (row.problem === "permission")
            entries.push(
                work(
                    "youtube",
                    `YouTube alerts for ${name} are off: NeonFlux cannot post in ${channel(row.channelId)}`,
                    `Give NeonFlux View channel, Send messages and Embed links in that channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (hubError)
            entries.push(
                work(
                    "youtube",
                    `YouTube alerts for ${name} may miss videos: ${hubError}`,
                    `NeonFlux asks YouTube again on its own, waiting longer after each failure. !youtube status ${name} shows the latest attempt`,
                ),
            )
    }
    return entries
}
// Followed channels NeonFlux turned off, with the fix, and streamers whose EventSub subscription or login lookup failed
async function readTwitch(ctx: QueryCtx, serverId: string) {
    const entries: Work[] = []
    for (const row of await twitchSubscriptions(ctx, serverId)) {
        const source = await twitchSource(ctx, row.twitchChannelId),
            name = source?.title ?? source?.login ?? row.twitchChannelId,
            hubError = source?.lastError
        // Twitch commands take a followed channel's name, so the steps name it as entries do
        const again = `then turn the alerts back on with !twitch add ${name} #channel`
        if (row.problem === "channel")
            entries.push(
                work(
                    "twitch",
                    `Twitch alerts for ${name} are off: Their channel ${channel(row.channelId)} is gone or cannot hold alerts`,
                    `Choose a text, announcement or forum channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (row.problem === "permission")
            entries.push(
                work(
                    "twitch",
                    `Twitch alerts for ${name} are off: NeonFlux cannot post in ${channel(row.channelId)}`,
                    `Give NeonFlux View channel, Send messages and Embed links in that channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (hubError)
            entries.push(
                work(
                    "twitch",
                    `Twitch alerts for ${name} may miss streams: ${hubError}`,
                    source?.stopped
                        ? `Check the Twitch login or revocation reason, then remove and add a working streamer. !twitch status ${name} shows the problem`
                        : `NeonFlux asks Twitch again on its own, waiting longer after each failure. !twitch status ${name} shows the latest attempt`,
                ),
            )
    }
    return entries
}
// Boards NeonFlux stopped, with the fix, and removed posts whose delete has an unknown outcome
async function readBoardProblems(ctx: QueryCtx, serverId: string) {
    const entries: Work[] = []
    for (const row of await readBoards(ctx, serverId)) {
        const again = `then turn it back on with !board set ${row.name} channel ${channel(row.channelId)}`
        if (row.problem === "channel")
            entries.push(
                work(
                    "boards",
                    `Board ${row.name} is stopped: Its channel ${channel(row.channelId)} is gone or cannot hold posts`,
                    `Choose a text or announcement channel with !board set ${row.name} channel #channel`,
                    row.updatedAt,
                ),
            )
        else if (row.problem === "permission")
            entries.push(
                work(
                    "boards",
                    `Board ${row.name} is stopped: NeonFlux cannot post in ${channel(row.channelId)}`,
                    `Give NeonFlux View channel, Send messages and Embed links in that channel, ${again}`,
                    row.updatedAt,
                ),
            )
    }
    const stale = await ctx.db
        .query("boardEntries")
        .withIndex("by_server_due", (q) =>
            q
                .eq("serverId", serverId)
                .eq("state", "removing")
                .lte("nextCheckAt", Date.now() - 60000),
        )
        .take(10)
    for (const row of stale)
        entries.push(
            work(
                "boards",
                `A board post in ${channel(row.postChannelId ?? row.sourceChannelId)} may not have been removed: The delete's outcome is unknown`,
                "Delete the post by hand if it is still there. NeonFlux does not try again",
                row.nextCheckAt,
            ),
        )
    return entries
}
// Counters NeonFlux turned off, with the fix
async function readCounterProblems(ctx: QueryCtx, serverId: string) {
    const entries: Work[] = []
    for (const row of await readCounters(ctx, serverId)) {
        const again = `then turn it back on with !counter set ${channel(row.channelId)} "${row.template}"`
        if (row.problem === "channel")
            entries.push(
                work(
                    "counters",
                    `A counter is off: Its channel ${channel(row.channelId)} is gone`,
                    `Remove it with !counter remove ${channel(row.channelId)} and add one for another channel`,
                    row.updatedAt,
                ),
            )
        else if (row.problem === "permission")
            entries.push(
                work(
                    "counters",
                    `A counter is off: NeonFlux cannot rename ${channel(row.channelId)}`,
                    `Give NeonFlux View channel and Manage channels in that channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (row.countProblem)
            entries.push(
                work(
                    "counters",
                    `A counter in ${channel(row.channelId)} cannot read its count, so the channel keeps its name`,
                    counterCountProblemText(row.countProblem),
                    row.updatedAt,
                ),
            )
    }
    return entries
}

// Giveaways with a problem. A card's post with an unknown outcome is already listed with the other posts
const GIVEAWAY_PROBLEMS = {
    channel: (no: number, where: string) =>
        [
            `Giveaway #${no} ended: Its channel ${where} is gone or cannot hold it`,
            "Start it again in another channel",
        ] as const,
    card: (no: number, where: string) =>
        [
            `Giveaway #${no} ended: Its card in ${where} was deleted`,
            `!giveaway show ${no} shows what was recorded`,
        ] as const,
    permission: (no: number, where: string) =>
        [
            `Giveaway #${no} cannot draw: NeonFlux cannot read its entries in ${where}`,
            "Give NeonFlux View channel and Read message history there. It tries again on its own",
        ] as const,
    "post-late": (no: number, where: string) =>
        [
            `Giveaway #${no} ended unposted: Its end passed before its card could go out in ${where}`,
            "Start it again once NeonFlux can post",
        ] as const,
    "post-failed": (no: number, where: string) =>
        [
            `Giveaway #${no} ended: Fluxer refused its card in ${where}`,
            "Fix NeonFlux's permissions there and start it again",
        ] as const,
    "result-failed": (no: number, where: string) =>
        [
            `The card of giveaway #${no} in ${where} could not be updated`,
            `!giveaway show ${no} names the outcome`,
        ] as const,
    "result-uncertain": (no: number, where: string) =>
        [
            `The update of giveaway #${no}'s card in ${where} is not confirmed`,
            `!giveaway show ${no} reads the card. NeonFlux never updates it twice`,
        ] as const,
    reaction: (no: number, where: string) =>
        [
            `NeonFlux could not add the entry emoji to giveaway #${no} in ${where}`,
            "Members can still add it, or give NeonFlux Add reactions there",
        ] as const,
}
async function readGiveawayProblems(ctx: QueryCtx, serverId: string) {
    const rows = await ctx.db
        .query("giveaways")
        .withIndex("by_problem", (q) => q.eq("serverId", serverId).gt("problemAt", 0))
        .order("desc")
        .take(RECOVERY_PER_SOURCE)
    const entries: Work[] = []
    for (const row of rows) {
        if (!row.problem || row.problem === "post-uncertain") continue
        const [what, fix] = GIVEAWAY_PROBLEMS[row.problem](row.giveawayNo, channel(row.channelId))
        entries.push(work("giveaways", what, fix, row.problemAt))
    }
    return entries
}

// Followed accounts NeonFlux turned off, with the fix, and accounts it cannot read, including a change in a service's answers
async function readFeeds(ctx: QueryCtx, serverId: string) {
    const entries: Work[] = []
    for (const row of await feedSubscriptions(ctx, serverId)) {
        const source = await feedSource(ctx, row.provider, row.accountId),
            service = feedProviderNames[row.provider],
            name = source?.handle ?? source?.name ?? row.accountId
        const again = `then turn the posts back on with !feed add ${row.provider} ${name} #channel`
        if (row.problem === "channel")
            entries.push(
                work(
                    "feeds",
                    `${service} posts of ${name} are off: Their channel ${channel(row.channelId)} is gone or cannot hold posts`,
                    `Choose a text, announcement or forum channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (row.problem === "permission")
            entries.push(
                work(
                    "feeds",
                    `${service} posts of ${name} are off: NeonFlux cannot post in ${channel(row.channelId)}`,
                    `Give NeonFlux View channel, Send messages and Embed links in that channel, ${again}`,
                    row.updatedAt,
                ),
            )
        else if (source?.lastError)
            entries.push(
                work(
                    "feeds",
                    `${service} posts of ${name} may be missed: ${source.lastError}`,
                    source.stopped
                        ? `Check the handle, then remove it and add the current one. !feed status ${name} shows the problem`
                        : `NeonFlux tries again on its own, waiting longer after each failure. !feed status ${name} shows the latest state`,
                ),
            )
    }
    return entries
}

// Channels a lockdown could not lock or restore, or whose write has an unknown outcome
async function readLockdownEntries(ctx: QueryCtx, serverId: string) {
    const lockdown = await readLockdown(ctx, serverId)
    if (!lockdown || lockdown.counts.uncertain + lockdown.counts.failed === 0) return []
    const entries: Work[] = []
    for (const state of ["uncertain", "failed"] as const)
        for (const row of await lockdownChannelsIn(ctx, serverId, state).take(RECOVERY_PER_SOURCE)) {
            const lock = row.phase === "lock",
                ended = lock ? "active" : "lifted"
            entries.push(
                work(
                    "lockdown",
                    state === "uncertain"
                        ? `NeonFlux could not confirm whether it ${lock ? "locked" : "restored"} ${channel(row.channelId)} in the lockdown`
                        : `The lockdown could not ${lock ? "lock" : "restore"} ${channel(row.channelId)}`,
                    state === "uncertain"
                        ? "!lockdown status reads the channel and settles it, and NeonFlux never repeats the change on its own"
                        : `Give NeonFlux Manage roles, then repeat !lockdown ${lock ? "on" : "off"} while the lockdown is ${ended}`,
                    lockdown.startedAt,
                ),
            )
        }
    return entries
}
// Jails whose edit has an unknown outcome, ends that could not run, and channels the jail role could not be denied. Any manager reads this
// inbox, so it names cases and not members
async function readJailEntries(ctx: QueryCtx, serverId: string, now: number) {
    const entries: Work[] = []
    const rows = await ctx.db
        .query("jailRecords")
        .withIndex("by_server_user", (q) => q.eq("serverId", serverId))
        .take(JAIL_RECORD_LIMIT)
    for (const row of rows) {
        if (entries.length >= RECOVERY_PER_SOURCE) break
        if (row.state === "jail-uncertain" || row.state === "release-uncertain")
            entries.push(
                work(
                    "jail",
                    `NeonFlux could not confirm a ${row.state === "jail-uncertain" ? "jail" : "release"}`,
                    `!mod recover ${row.state === "jail-uncertain" ? row.caseNo : (row.releaseCaseNo ?? row.caseNo)} reads the member and settles it, and NeonFlux never repeats the change on its own`,
                    row.createdAt,
                ),
            )
        else if (row.state === "active" && row.releaseAt !== undefined && row.releaseAt < now - JAIL_RELEASE_LATE_MS)
            entries.push(
                work(
                    "jail",
                    `The jail of case #${row.caseNo} ended, but NeonFlux could not release the member yet`,
                    "Give NeonFlux Manage roles and move its role above the jail role. It tries again every 10 minutes",
                    row.releaseAt,
                ),
            )
    }
    const setup = (await readJailSettings(ctx, serverId))?.setup
    for (const problem of setup?.problems.slice(0, RECOVERY_PER_SOURCE) ?? [])
        entries.push(
            work(
                "jail",
                problem.state === "uncertain"
                    ? `NeonFlux could not confirm the jail overwrite on ${channel(problem.channelId)}`
                    : `NeonFlux could not write the jail overwrite on ${channel(problem.channelId)}`,
                "Give NeonFlux Manage roles in that channel, then run !jail setup, which reads each channel first",
                setup!.updatedAt,
            ),
        )
    return entries
}
// How many members have their bot-only rights suspended, which only the server owner lifts. Any manager reads this inbox, so it names nobody
async function readRightsEntries(ctx: QueryCtx, serverId: string) {
    const rows = await ctx.db
        .query("rightsSuspensions")
        .withIndex("by_server_user", (q) => q.eq("serverId", serverId))
        .take(RIGHTS_SUSPENDED_COUNT_LIMIT)
    if (!rows.length) return []
    return [
        work(
            "rights",
            `${rows.length} ${rows.length === 1 ? "member's" : "members'"} bot-only rights are suspended, after a limit or anti-nuke`,
            "Staff see who with !mod rights status. Check what happened, then the server owner can run !mod rights clear @member",
            Math.max(...rows.map((row) => row.at)),
        ),
    ]
}
// Anti-nuke incidents whose native response has an unknown outcome or failed. A failed one means the account may still be acting
async function readAntiNukeEntries(ctx: QueryCtx, serverId: string, now: number) {
    const rows = [
        ...(await ctx.db
            .query("antiNukeIncidents")
            .withIndex("by_server_outcome", (q) => q.eq("serverId", serverId).eq("outcome", "uncertain"))
            .order("desc")
            .take(RECOVERY_PER_SOURCE)),
        ...(await ctx.db
            .query("antiNukeIncidents")
            .withIndex("by_server_outcome", (q) => q.eq("serverId", serverId).eq("outcome", "failed"))
            .order("desc")
            .take(RECOVERY_PER_SOURCE)),
    ].filter((row) => row.outcome === "uncertain" || row.createdAt > now - RECOVERY_SETTLED_MS)
    return rows.map((row) =>
        work(
            "antinuke",
            row.outcome === "uncertain"
                ? `Anti-nuke incident ${row.incidentNo}: NeonFlux could not confirm its response`
                : `Anti-nuke incident ${row.incidentNo}: NeonFlux could not stop the account`,
            `!antinuke incident ${row.incidentNo} reads the member and settles it. Check what they can still do`,
            row.createdAt,
        ),
    )
}

async function readCurrent(ctx: QueryCtx, serverId: string, now: number) {
    // Custom commands and autoresponders start on, so having none yet is not a problem
    const entries: RecoveryEntry[] = (await readSetupSections(ctx, serverId))
        .filter((section) => section.state === "setup" && section.id !== "custom" && section.id !== "auto")
        .map((section) => ({ kind: "feature", feature: section.id }))
    const defcon = moderationConfig(await readModeration(ctx, serverId)).defcon
    if (defcon < 3)
        entries.push(
            work(
                "defcon",
                `DEFCON ${defcon} is active, so NeonFlux pauses automatic posts and other automation`,
                "!defcon status, then !defcon set 3 once the threat has passed",
            ),
        )
    // Metadata logs count their failed and unknown deliveries, security alerts among them, so the inbox reads one row
    const logs = await ctx.db
        .query("metadataLogSettings")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    if (logs && logs.failed + logs.uncertain > 0)
        entries.push(
            work(
                "logs",
                `Metadata logs: ${logs.failed} ${logs.failed === 1 ? "delivery" : "deliveries"} failed and ${logs.uncertain} ${logs.uncertain === 1 ? "has" : "have"} an unknown outcome. Security alerts are delivered the same way`,
                "!logs events list, then !logs delivery show <record> or !logs delivery reconcile <record>",
            ),
        )
    const helpDesk = await readHelpDesk(ctx, serverId)
    if (helpDesk?.warnedAt !== undefined && helpDesk.warnedAt > now - RECOVERY_SETTLED_MS)
        entries.push(
            work(
                "helpdesk",
                "The server neared Fluxer's limit of 1,000 active threads",
                "Close or archive old forum posts, or let NeonFlux apply each channel's auto-archive time with !helpdesk archive on",
                helpDesk.warnedAt,
            ),
        )
    const check = await ctx.db
        .query("dashboardSetupJobs")
        .withIndex("by_server", (q) => q.eq("serverId", serverId))
        .unique()
    if (check?.state === "done" && check.checkedAt !== undefined)
        entries.push(
            ...(check.problems as SetupProblem[]).map((problem) => ({
                kind: "setup" as const,
                at: check.checkedAt!,
                problem,
            })),
        )
    return entries
}

/** Every source's entries, current state first and then newest first. removalsBefore reads only the next page of stopped role removals */
export async function readRecoveryInbox(
    ctx: QueryCtx,
    serverId: string,
    removalsBefore?: number,
): Promise<RecoveryInbox> {
    const now = Date.now()
    const removals = await readRemovals(ctx, serverId, removalsBefore),
        next = removals.next !== undefined ? { nextRemovalsBefore: removals.next } : {}
    if (removalsBefore !== undefined) return { serverId, entries: removals.entries, truncated: false, ...next }
    // The first page of stopped role removals is always shown whole, so the next page starts right after what the inbox shows
    const entries = [
        ...(await readCurrent(ctx, serverId, now)),
        ...(await readPublishing(ctx, serverId, now)),
        ...(await readRoles(ctx, serverId)),
        ...(await readTemporaryRoles(ctx, serverId, now)),
        ...(await readTickets(ctx, serverId)),
        ...(await readCleanup(ctx, serverId, now)),
        ...(await readGreetings(ctx, serverId, now)),
        ...(await readBlockedDeliveries(ctx, serverId)),
        ...(await readYoutube(ctx, serverId)),
        ...(await readTwitch(ctx, serverId)),
        ...(await readLockdownEntries(ctx, serverId)),
        ...(await readAntiNukeEntries(ctx, serverId, now)),
        ...(await readJailEntries(ctx, serverId, now)),
        ...(await readRightsEntries(ctx, serverId)),
        ...(await readFeeds(ctx, serverId)),
        ...(await readCounterProblems(ctx, serverId)),
        ...(await readGiveawayProblems(ctx, serverId)),
        ...(await readBoardProblems(ctx, serverId)),
    ]
    const at = (entry: RecoveryEntry) =>
        entry.kind === "feature" ? Number.MAX_SAFE_INTEGER : (entry.at ?? Number.MAX_SAFE_INTEGER)
    entries.sort((a, b) => at(b) - at(a))
    const room = RECOVERY_LIMIT - removals.entries.length,
        shown = [...entries.slice(0, room), ...removals.entries].sort((a, b) => at(b) - at(a))
    return { serverId, entries: shown, truncated: entries.length > room, ...next }
}

/** What !recovery lists */
export const list = serviceQuery({
    args: { request: v.any() },
    handler: (ctx, { request }) => {
        const input = decode(RecoveryListRequest, request)
        return readRecoveryInbox(ctx, input.serverId, input.removalsBefore)
    },
})
/** The dashboard's recovery inbox, for server managers */
export const inbox = query({
    args: { sessionToken: v.string(), serverId: v.string(), removalsBefore: v.optional(v.number()) },
    handler: async (ctx, { sessionToken, serverId, removalsBefore }): Promise<RecoveryInbox> => {
        await dashboardSession(ctx, sessionToken, serverId)
        return readRecoveryInbox(ctx, serverId, removalsBefore)
    },
})