1
0
Fork 0

Compare commits

...

10 commits

Author SHA1 Message Date
6cd94c31f8 v0.7.0 - add Labor Crew admin panel, fix npc-dialogue countdown spacing 2026-10-07 23:29:02 -04:00
0370df6c2d feat(game-structures): add Labor Crew admin panel for staffing writes
Wire the previously orphaned LaborCrewPanel into the game-structures
editor so staff can set actual headcount and per-worker wage for a
labor classification. Adds a laborCrewPanel ui field on the edit view,
a POST route under /api/game-structures that authenticates and gates on
game-structures:update, delegates to the canonical setLaborHeadcount
service (enforcing caps and wage logic), and an integration test
covering auth, validation, and cap enforcement.
2026-10-07 23:28:35 -04:00
02307aa2ee fix(npc-dialogue): split countdown units into controlled-gap cells
The countdown rendered each time unit with a raw monospace space,
which reads wide and odd when inline with proportional text. Split the
value into per-unit inline-flex cells separated by a CSS gap so spacing
stays consistent, and cover the new markup in the interpolate
integration test.
2026-10-07 23:28:31 -04:00
375023f708 fix(mcp): backfill missing capability columns on payload_mcp_api_keys
The plugin generates one checkbox column per enabled collection
(<slug>_find/_create/_update/_delete), but only recent feature migrations
added theirs; 256 columns for older collections were never created, so any
query against the keys table failed with 'column does not exist' (HTTP 500
on list/create). Adds an idempotent ALTER TABLE IF NOT EXISTS migration for
all missing columns, registered in the migration index with a full-schema
snapshot sidecar (migrate:create reports no diff since the snapshot chain
already contained them).
2026-10-07 18:26:42 -04:00
f97912f1c1 fix(mcp): gate API-key collection with system:admin-access so superusers can issue keys
The MCP plugin's key collection was gated by hasRoles(), which reads only
the legacy roles enum column. All current admins authenticate through
dynamic roleDocs superuser roles, so nobody could create an MCP API key
and every client of /api/mcp got 401. Both override blocks (MCP keys and
the AI plugin instructions) now use requirePermission('system:admin-access'),
and the sync-only admin.hidden checks were dropped in favor of the read
gate, matching the repo's requireAdminPageAccess pattern.

Adds tests/int/mcp-api-keys.int.spec.ts covering the plain-user rejection,
dynamic-superuser key creation with HMAC index resolution (mirroring the
plugin's resolveAccessSettings), explicit system:admin-access grants, and
read visibility.
2026-10-07 18:21:06 -04:00
a96eddf32c feat(npc-dialogue): bigger flow handles + delete edges via Delete
- Enlarge flow-editor wire handles from size-2 (8px) to size-3 (12px) so
  they are easier to click and grab.
- Select an edge by clicking it, then remove it with the Delete key.
  Selection is tracked in state and the highlight renders through BaseEdge
  stroke props so the chosen line stands out.
- Edges are a derived projection, so deletion scrubs the hop from the
  source node data via a new pure removeHopFromNode() helper in dialogue.ts
  (choice row, condition branch, or single continuation).
- Add tests/int/npc-dialogue-remove-hop.int.spec.ts (4 tests).
2026-10-07 14:25:14 -04:00
538b7d4c4c feat(npc-dialogue): reorder choices in the dialogue editor
Choice rows in the dialogue node editor now have up/down buttons so a
choice can be moved up or down into the desired order, which is the
order shown to the player. The swap lives in a pure reorderChoice
helper (no-op at the edges, input not mutated) with a focused test.
2026-10-07 14:01:00 -04:00
9f0f7db612 feat(npc-dialogue): auto-grow the dialogue line box to fit its content
The Line textarea in the dialogue node editor grows to fit its content
up to a 200px default max, so long lines no longer scroll in a
fixed-height box. It stays drag-resizable (resize-y) and the user can
still expand it past the max.

The auto-grow hooks run above the early-return guard so their call
order never changes, fixing a Rules of Hooks violation the change would
otherwise introduce.
2026-10-07 14:00:15 -04:00
f643028638 feat(npc-dialogue): let event flag effects target self, global, or a specific user
Event node flag effects previously always wrote the active participant's
flag. A flag's identity is (owner, key), so the same key can hold
independent values for different owners, but there was no way to target
them from the editor.

- Add flagTarget ("self" | "global" | "user") + flagTargetUserId to
  NpcDialogueEffect. "self" (default) keeps current behavior.
- Add resolveFlagOwner (flags.ts) to map a scope onto the player-flags
  user column; "user" with no id falls back to the participant so a
  misconfigured effect never nudges the global flag.
- Move applyFlagEffect into flags.ts, parameterized by resolved owner;
  the runtime action resolves the owner and delegates.
- Add a Target control (+ user picker) to the event node editor and
  validateGraph enforcement for the "user" scope.
- Integration tests cover owner resolution and self/global/user writes.
2026-10-07 13:33:52 -04:00
2231cc86ee feat(dashboard): flag restricted events with a lock icon in Recent Events 2026-10-07 13:07:23 -04:00
25 changed files with 40238 additions and 158 deletions

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.6.0",
"version": "0.7.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -180,6 +180,7 @@ export default async function HomePage() {
system: e.system ?? true,
actor: e.actor as number | User | null | undefined,
structure: e.structure as number | GameStructure | null | undefined,
visibility: (e.visibility as "public" | "restricted" | null) ?? "public",
}));
// Fetch active campaigns for the sidebar

View file

@ -9,7 +9,7 @@ import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
import type {
ChoiceGate,
DialogueFlagOp,
@ -127,9 +127,12 @@ async function runEffect(
if (!key) break;
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
const amount = effect.flagAmount ?? 0;
// Resolve who the flag belongs to (self / global / a specific user) so
// same-named flags for different owners never collide.
const owner = resolveFlagOwner(effect.flagTarget, effect.flagTargetUserId, userId);
await applyFlagEffect(
payload,
userId,
owner,
key,
op,
amount,
@ -149,115 +152,6 @@ async function runEffect(
}
}
/** Create-or-update a player flag according to the effect's write mode. A
* positive `delayMinutes` stamps the flag with a future `activatesAt`, so it
* reads as false until then (conditions fail, countdowns tick toward it). */
async function applyFlagEffect(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,
key: string,
op: DialogueFlagOp,
amount: number,
effectText?: string,
delayMinutes?: number,
): Promise<void> {
const activatesAt =
delayMinutes && delayMinutes > 0
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
: null;
const existing = await payload.find({
collection: "player-flags",
where: {
user: { equals: userId },
key: { equals: key },
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const doc = existing.docs[0];
if (op === "set_true" || op === "set_false") {
const boolValue = op === "set_true";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_number") {
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_text") {
const textValue = effectText ?? "";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
}
return;
}
// add: numeric flags accumulate; boolean flags convert (true = 1).
const current = doc
? doc.flagType === "number"
? doc.numberValue ?? 0
: doc.boolValue
? 1
: 0
: 0;
const numberValue = current + amount;
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "number", numberValue, activatesAt },
overrideAccess: true,
});
}
}
/**
* Evaluate a dialogue `condition` node against the reading user's live
* web-app state (player flags). The node is looked up server-side from the

View file

@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import { setLaborHeadcount } from "@/lib/base/staffing";
import { hasPermission } from "@/utils/access-control/hasPermission";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Admin-panel labor-crew write for the game-structures editor. Consumed by the
* Labor Crew panel (`LaborCrewPanel`) on the game-structures edit view: it sets
* the actual headcount and per-worker wage for a labor classification on a
* structure, delegating to the canonical `setLaborHeadcount` service (which
* enforces caps, wage logic, and emits the resulting events).
*
* Access mirrors the game-structures collection update rule.
*/
export async function POST(req: NextRequest) {
const payload = await getPayload({ config: await config });
const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false });
if (!user) {
return NextResponse.json({ success: false, error: "Unauthorized" }, { status: 401 });
}
if (!(await hasPermission(payload, user, "game-structures:update"))) {
return NextResponse.json({ success: false, error: "Forbidden" }, { status: 403 });
}
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ success: false, error: "Invalid JSON body" }, { status: 400 });
}
const { structureId, classificationId, headcount, unitSalary } = (body ?? {}) as {
structureId?: unknown;
classificationId?: unknown;
headcount?: unknown;
unitSalary?: unknown;
};
if (!Number.isInteger(structureId) || !Number.isInteger(classificationId)) {
return NextResponse.json(
{ success: false, error: "structureId and classificationId are required." },
{ status: 400 },
);
}
try {
await setLaborHeadcount(payload, {
structureId: structureId as number,
classificationId: classificationId as number,
headcount: Number(headcount) || 0,
unitSalary: Number(unitSalary) || 0,
});
return NextResponse.json({ success: true });
} catch (err) {
payload.logger.error(
`[game-structures] set-labor-headcount failed: ${
err instanceof Error ? err.message : String(err)
}`,
);
return NextResponse.json(
{ success: false, error: err instanceof Error ? err.message : "Labor update failed." },
{ status: 400 },
);
}
}

View file

@ -536,5 +536,14 @@ export const GameStructures: CollectionConfig = {
],
},
},
{
name: "laborCrewPanel",
type: "ui",
admin: {
components: {
Field: "@/components/admin/game/LaborCrewField",
},
},
},
],
};

View file

@ -0,0 +1,268 @@
"use client";
import { useEffect, useState } from "react";
import { UsersIcon } from "lucide-react";
import { toast, useDocumentInfo, useField } from "@payloadcms/ui";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import type { LaborClassificationOption } from "@/lib/base/types";
interface LaborCrew {
classificationId: number;
classificationName: string;
headcount: number;
unitSalary: number;
requiredHeadcount: number;
maxHeadcount: number;
enforcedSalary: number | null;
}
interface LaborEdit {
headcount: string;
unitSalary: string;
}
export function LaborCrewPanel() {
const documentInfo = useDocumentInfo();
const laborRequirementsField = useField<{
classificationId?: number | null;
requiredHeadcount?: number | null;
maxHeadcount?: number | null;
enforcedSalary?: number | null;
}[]>({
path: "laborRequirements",
});
const [crew, setCrew] = useState<LaborCrew[]>([]);
const [edits, setEdits] = useState<Record<number, LaborEdit>>({});
const [loadingClassifications, setLoadingClassifications] = useState(false);
const [savingId, setSavingId] = useState<number | null>(null);
// Fetch classifications and current crew from REST
useEffect(() => {
let cancelled = false;
async function loadData() {
setLoadingClassifications(true);
try {
const [classificationsRes, crewRes] = await Promise.all([
fetch("/api/labor-classifications?depth=0"),
fetch(`/api/npc-staffing?where.structure.id=${documentInfo.id}&depth=0`),
]);
if (cancelled) return;
const classifications = (await classificationsRes.json()).docs as LaborClassificationOption[];
const crewDocs = await crewRes.json();
// Build crew list from laborRequirements + current npc-staffing docs
const requirementList = laborRequirementsField.value ?? [];
const newCrew: LaborCrew[] = requirementList.flatMap((req) => {
const classification = classifications.find(
(c) => c.id === req.classificationId,
);
if (!classification) return [];
const crewMembers = (crewDocs.docs ?? []).filter(
(m: any) =>
m.positionType === "labor" &&
m.laborClassification?.id === classification.id,
);
const headcount = crewMembers.reduce((sum: number, m: any) => sum + (m.headcount ?? 1), 0);
const unitSalary = crewMembers[0]?.salary ?? classification.defaultUnitSalary ?? 0;
return {
classificationId: classification.id,
classificationName: classification.name,
headcount,
unitSalary,
requiredHeadcount: req.requiredHeadcount ?? 0,
maxHeadcount: req.maxHeadcount ?? Infinity,
enforcedSalary: req.enforcedSalary ?? null,
};
});
setCrew(newCrew);
} catch {
toast.error("Failed to load labor data");
} finally {
setLoadingClassifications(false);
}
}
if (documentInfo.id) loadData();
return () => { cancelled = true; };
}, [documentInfo.id, laborRequirementsField.value]);
function getEdit(crewItem: LaborCrew): LaborEdit {
return edits[crewItem.classificationId] ?? {
headcount: String(crewItem.headcount),
unitSalary: String(crewItem.unitSalary),
};
}
function updateEdit(crewItem: LaborCrew, field: keyof LaborEdit, value: string) {
setEdits((current) => ({
...current,
[crewItem.classificationId]: {
...getEdit(crewItem),
[field]: value,
},
}));
}
async function handleSave(crewItem: LaborCrew) {
const edit = getEdit(crewItem);
const headcount = Number(edit.headcount);
const unitSalary = Number(edit.unitSalary) || 0;
if (!Number.isInteger(headcount) || headcount < 0) {
toast.error("Headcount must be a whole number of 0 or more.");
return;
}
if (!Number.isFinite(unitSalary) || unitSalary < 0) {
toast.error("Wage cannot be negative.");
return;
}
setSavingId(crewItem.classificationId);
try {
const response = await fetch("/api/game-structures/set-labor-headcount", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
structureId: documentInfo.id,
classificationId: crewItem.classificationId,
headcount,
unitSalary,
}),
});
const result = await response.json();
if (!result.success) {
toast.error(result.error ?? "Labor update failed");
return;
}
// Update local state
setCrew((current) =>
current.map((c) =>
c.classificationId === crewItem.classificationId
? { ...c, headcount, unitSalary }
: c,
),
);
setEdits((current) => {
const next = { ...current };
delete next[crewItem.classificationId];
return next;
});
toast.success(`${crewItem.classificationName} crew updated`);
} catch {
toast.error("Labor update failed");
} finally {
setSavingId(null);
}
}
if (!documentInfo.id) return null;
return (
<Card className="mt-6">
<CardHeader className="gap-2">
<CardTitle className="flex items-center gap-2">
<UsersIcon className="size-4 text-muted-foreground" />
Labor Crew
</CardTitle>
<CardDescription>
Set actual headcount and wages per labor classification for this structure.
Changes apply immediately via the staffing system.
</CardDescription>
</CardHeader>
<CardContent>
{loadingClassifications ? (
<p className="text-sm text-muted-foreground">Loading crew data...</p>
) : crew.length === 0 ? (
<p className="text-sm text-muted-foreground">No labor classifications configured for this structure.</p>
) : (
<div className="flex flex-col gap-3">
{crew.map((item, index) => {
const edit = getEdit(item);
const isSaving = savingId === item.classificationId;
return (
<div key={item.classificationId}>
{index > 0 && <Separator />}
<div className="flex flex-col gap-3 py-3 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-medium">
{item.classificationName}: {item.headcount} hired · {item.requiredHeadcount} required · max {item.maxHeadcount}
</p>
<p className="font-mono text-sm tabular-nums text-muted-foreground">
{item.unitSalary}/tick each · {item.unitSalary * item.headcount}/tick total
</p>
</div>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor={`labor-headcount-${item.classificationId}`}>
Headcount
</Label>
<Input
id={`labor-headcount-${item.classificationId}`}
type="number"
min={0}
max={item.maxHeadcount}
step={1}
inputMode="numeric"
value={edit.headcount}
onChange={(e) => updateEdit(item, "headcount", e.target.value)}
disabled={isSaving}
/>
</div>
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor={`labor-wage-${item.classificationId}`}>
Wage per worker
</Label>
<Input
id={`labor-wage-${item.classificationId}`}
type="number"
min={0}
step="any"
value={edit.unitSalary}
onChange={(e) => updateEdit(item, "unitSalary", e.target.value)}
disabled={isSaving || item.enforcedSalary !== null}
/>
{item.enforcedSalary !== null && (
<p className="text-xs text-muted-foreground">
Enforced by structure blueprint ({item.enforcedSalary}/tick)
</p>
)}
</div>
<Button
variant="outline"
size="sm"
onClick={() => void handleSave(item)}
disabled={isSaving}
>
{isSaving ? "Saving..." : "Apply"}
</Button>
</div>
</div>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
);
}
export default LaborCrewPanel;

View file

@ -1,7 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { XIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react";
import {
Dialog,
@ -26,6 +26,7 @@ import type {
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
interface NodeEditDialogProps {
readonly node: DialogueNode | null;
@ -64,6 +65,10 @@ const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls
* inside the box from here; the user can still drag-resize it taller. */
const MAX_LINE_HEIGHT_PX = 200;
/** Short readable label for a node in the target pickers, with a text snippet. */
function nodeLabel(node: DialogueNode): string {
const d = node.data;
@ -107,15 +112,62 @@ function nodeLabel(node: DialogueNode): string {
export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
// Users for the "Specific user" flag target. Fetched once per open; the
// admin context is already authenticated, so cookie auth is enough.
const [users, setUsers] = useState<{ id: number; username: string }[]>([]);
useEffect(() => {
let active = true;
if (!open) return;
fetch("/api/users?limit=1000&depth=0")
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!active) return;
const list = Array.isArray(data?.docs) ? data.docs : [];
setUsers(
list
.filter((u: { username?: unknown }) => Boolean(u?.username))
.map((u: { id: number; username: string }) => ({
id: u.id,
username: `${u.username} (id ${u.id})`,
})),
);
})
.catch(() => {
if (active) setUsers([]);
});
return () => {
active = false;
};
}, [open]);
useEffect(() => {
setDraft(node?.data ?? null);
}, [node?.id, open]);
if (!node || !draft) return null;
const patch = (partial: Partial<DialogueNodeData>) =>
setDraft((prev) => (prev ? { ...prev, ...partial } : prev));
const lineRef = useRef<HTMLTextAreaElement>(null);
/** Auto-grow the line box to its content up to MAX_LINE_HEIGHT_PX so long
* lines do not scroll in a fixed-height box. The user can still drag-resize
* it taller; typing re-sizes it to fit. */
const autoSizeLine = useCallback(() => {
const el = lineRef.current;
if (!el) return;
el.style.height = "auto";
el.style.height = `${Math.min(el.scrollHeight, MAX_LINE_HEIGHT_PX)}px`;
}, []);
useEffect(() => {
autoSizeLine();
}, [draft?.body, autoSizeLine]);
// Guard lives below every hook so their call order never changes: on the
// first render draft is still null, and returning early here would skip the
// hooks defined above it on later renders (a Rules of Hooks violation).
if (!node || !draft) return null;
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
patch({ effect: { type: "notify", ...draft.effect, ...partial } });
@ -133,6 +185,13 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
const removeChoice = (index: number) =>
patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) });
/** Swap a choice with its neighbour so choices can be reordered. No-op at
* the ends, so the buttons can be disabled there. */
const moveChoice = (index: number, direction: -1 | 1) => {
const ordered = reorderChoice(draft.choices ?? [], index, direction);
if (ordered) patch({ choices: ordered });
};
/** Toggle/update a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
patch({
@ -183,11 +242,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Line</Label>
<Textarea
ref={lineRef}
value={draft.body ?? ""}
onChange={(e) => patch({ body: e.target.value || undefined })}
onChange={(e) => {
patch({ body: e.target.value || undefined });
autoSizeLine();
}}
placeholder="The NPC says…"
rows={4}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
@ -230,6 +293,30 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</div>
{(draft.choices ?? []).map((choice, index) => (
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-2">
<div className="flex items-center justify-end gap-1">
<Button
type="button"
variant="outline"
size="icon"
aria-label="Move choice up"
disabled={index === 0}
onClick={() => moveChoice(index, -1)}
className="h-6 w-6 border-white/20 text-white/70 hover:bg-zinc-800 disabled:opacity-30"
>
<ChevronUpIcon className="size-3.5" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
aria-label="Move choice down"
disabled={index === (draft.choices?.length ?? 0) - 1}
onClick={() => moveChoice(index, 1)}
className="h-6 w-6 border-white/20 text-white/70 hover:bg-zinc-800 disabled:opacity-30"
>
<ChevronDownIcon className="size-3.5" />
</Button>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Button text</Label>
<Input
@ -433,6 +520,54 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Target
</Label>
<select
value={draft.effect.flagTarget ?? "self"}
onChange={(e) =>
patchEffect({
flagTarget: e.target.value as "self" | "global" | "user",
// Leave the target user id set only in the "user" scope so
// switching away never leaves a dangling owner behind.
flagTargetUserId:
e.target.value === "user"
? draft.effect?.flagTargetUserId ?? users[0]?.id ?? undefined
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="self">Self (this player)</option>
<option value="global">Global (everyone, same key)</option>
<option value="user">Specific user</option>
</select>
{draft.effect.flagTarget === "user" && (
<select
value={draft.effect.flagTargetUserId ?? ""}
onChange={(e) =>
patchEffect({
flagTargetUserId: e.target.value
? Number(e.target.value)
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">No player</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.username}
</option>
))}
</select>
)}
<p className="text-[10px] text-white/40">
A flag's identity is (owner, key): the same key holds independent
values for each target. Defaults to this player.
</p>
</div>
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Write
</Label>

View file

@ -33,7 +33,7 @@ import type {
FlowData,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";
import { RoutedFlowEdge } from "./RoutedFlowEdge";
@ -96,6 +96,7 @@ function FlowEditor() {
const [paneMenu, setPaneMenu] = useState<PaneMenu>(null);
const [expanded, setExpanded] = useState(false);
const [snap, setSnap] = useState(true);
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
const lastSerialized = useRef<string>("");
const menuRef = useRef<HTMLDivElement | null>(null);
@ -133,13 +134,15 @@ function FlowEditor() {
// unrelated cards instead of slicing through them.
const syncedEdges = useMemo<Edge[]>(
() =>
deriveEdges(nodes as DialogueNode[]).map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
})),
[nodes],
deriveEdges(nodes as DialogueNode[])
.map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
selected: edge.id === selectedEdgeId,
})),
[nodes, selectedEdgeId],
);
const serialize = useCallback((nds: Node[]) => {
@ -172,6 +175,12 @@ function FlowEditor() {
[onNodesChange],
);
// Clicking the pane or an edge clears node selection; edge selection lives
// in its own state so it survives the node re-render.
const clearNodeSelection = useCallback(() => {
setNodes((nds) => nds.map((n) => (n.selected ? { ...n, selected: false } : n)));
}, [setNodes]);
useEffect(() => {
if (!pendingPositionSave.current) return;
pendingPositionSave.current = false;
@ -250,6 +259,25 @@ function FlowEditor() {
[nodes, setNodes, serialize, editingNodeId],
);
/**
* Deletes one edge. Edges are derived, so this scrubs the hop it represents
* from the source node data: a choice row, a condition branch, or the single
* continuation. `sourceHandle` identifies which one (c0..cN / true / false /
* undefined).
*/
const deleteEdge = useCallback(
(edge: Edge) => {
const source = (nodes as DialogueNode[]).find((n) => n.id === edge.source);
if (!source) return;
const next = (nodes as DialogueNode[]).map((n) =>
n.id === edge.source ? removeHopFromNode(n, edge.sourceHandle) : n,
);
setNodes(next);
serialize(next);
},
[nodes, setNodes, serialize],
);
const onNodeContextMenu = useCallback(
(e: ReactMouseEvent, node: Node) => {
e.preventDefault();
@ -359,8 +387,23 @@ function FlowEditor() {
const onPaneClick = useCallback(() => {
setContextMenu(null);
setPaneMenu(null);
setSelectedEdgeId(null);
}, []);
/**
* Selects an edge so it can be removed with the Delete key. Edges are a
* derived projection, so this only toggles selection: a second click on the
* same edge clears it, and either way node selection is cleared first.
*/
const onEdgeClick = useCallback(
(e: ReactMouseEvent, edge: Edge) => {
e.stopPropagation();
setSelectedEdgeId((prev) => (prev === edge.id ? null : edge.id));
clearNodeSelection();
},
[clearNodeSelection],
);
const validation = useMemo(() => validateGraph(nodes as DialogueNode[]), [nodes]);
// Close both context menus on escape / pointer outside.
@ -416,6 +459,16 @@ function FlowEditor() {
) {
return;
}
// An edge selection takes precedence over node selection.
if (selectedEdgeId) {
const edge = syncedEdges.find((candidate) => candidate.id === selectedEdgeId);
if (edge) {
e.preventDefault();
setSelectedEdgeId(null);
deleteEdge(edge);
}
return;
}
const selected = nodes.filter((n) => n.selected).map((n) => n.id);
if (selected.length === 0) return;
e.preventDefault();
@ -423,7 +476,7 @@ function FlowEditor() {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [nodes, editingNodeId, contextMenu, paneMenu, deleteNodes]);
}, [nodes, editingNodeId, contextMenu, paneMenu, selectedEdgeId, syncedEdges, deleteEdge, deleteNodes]);
const buttonClass =
"px-2 py-1 text-[10px] font-medium rounded border transition-colors cursor-pointer";
@ -545,6 +598,7 @@ function FlowEditor() {
// Single click selects (React Flow default); double-click edits.
onNodeDoubleClick={(_e, node) => setEditingNodeId(node.id)}
onNodeContextMenu={onNodeContextMenu}
onEdgeClick={onEdgeClick}
onPaneClick={onPaneClick}
onPaneContextMenu={onPaneContextMenu}
nodeTypes={nodeTypes}
@ -566,10 +620,10 @@ function FlowEditor() {
</div>
<p className="text-[10px] text-zinc-500">
Click a node to select it, double-click to edit. Select and press Del (or right-click) to
delete. Double-click the canvas for a new dialogue node; right-click it for any type. Drag
a row&apos;s dot to wire that exact choice or branch. Use Expand to fill the screen (Esc to
shrink).
Click a node to select it, double-click to edit. Click an edge to select it, then press Del
(or right-click a node) to delete. Double-click the canvas for a new dialogue node; right-click
it for any type. Drag a row&apos;s dot to wire that exact choice or branch. Use Expand to fill
the screen (Esc to shrink).
</p>
{contextMenu && (

View file

@ -106,7 +106,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id={`c${index}`}
type="source"
position={position}
className="!size-2 !bg-amber-400/80"
className="!size-3 !bg-amber-400/80"
style={{ right: -16 }}
/>
</li>
@ -183,7 +183,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id="true"
type="source"
position={position}
className="!size-2 !bg-emerald-400/80"
className="!size-3 !bg-emerald-400/80"
style={{ top: "auto", bottom: 26 }}
/>
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-rose-300/80">
@ -194,7 +194,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id="false"
type="source"
position={position}
className="!size-2 !bg-rose-400/80"
className="!size-3 !bg-rose-400/80"
style={{ bottom: 4 }}
/>
</div>
@ -214,10 +214,10 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
</div>
{genericSource && (
<Handle type="source" position={position} className="!size-2 !bg-white/60" />
<Handle type="source" position={position} className="!size-3 !bg-white/60" />
)}
{!d.isStart && (
<Handle type="target" position={inputPosition} className="!size-2 !bg-white/60" />
<Handle type="target" position={inputPosition} className="!size-3 !bg-white/60" />
)}
</div>
);

View file

@ -36,6 +36,7 @@ export function RoutedFlowEdge({
targetPosition,
markerEnd,
label,
selected,
}: EdgeProps) {
const nodeLookup = useStore((s) => s.nodeLookup);
@ -71,7 +72,12 @@ export function RoutedFlowEdge({
return (
<>
<BaseEdge id={id} path={path} markerEnd={markerEnd} />
<BaseEdge
id={id}
path={path}
markerEnd={markerEnd}
{...(selected ? { stroke: "#67e8f9", strokeWidth: 5, strokeDasharray: "8 5" } : {})}
/>
{labelText ? (
<EdgeLabelRenderer>
<div

View file

@ -1,6 +1,6 @@
import type { GameStructure, User } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { BookOpenTextIcon, ScrollTextIcon } from "lucide-react";
import { BookOpenTextIcon, LockIcon, ScrollTextIcon } from "lucide-react";
import { formatType } from "@/utils/event-log/formatType";
interface EventEntry {
@ -11,6 +11,7 @@ interface EventEntry {
system: boolean;
actor?: number | User | null;
structure?: number | GameStructure | null;
visibility?: "public" | "restricted" | null;
}
interface RecentEventsProps {
@ -86,6 +87,9 @@ export function RecentEvents({ events, currentUserId }: RecentEventsProps) {
</span>
)}
<span className="capitalize">{formatType(event.type)}</span>
{event.visibility === "restricted" && (
<LockIcon className="size-3 text-amber-400 shrink-0" />
)}
</div>
<span className={`min-w-0 ${isNarrative ? "text-amber-100/90" : ""}`}>
{event.message}

View file

@ -329,12 +329,20 @@ function Countdown({ value }: { value: string }) {
const remaining = target - now;
if (remaining <= 0) return <span className="font-mono text-emerald-400">ready</span>;
// Each unit is its own inline-flex cell so the gap between them is controlled
// (a monospace font's raw space reads wide/odd inline with proportional text).
return (
<span
className="font-mono tabular-nums text-cyan-300"
className="inline-flex items-center gap-1.5 font-mono tabular-nums text-cyan-300"
title={new Date(target).toISOString()}
>
{formatRemaining(remaining)}
{formatRemaining(remaining)
.split(" ")
.map((unit, i) => (
<span key={i} className="whitespace-nowrap">
{unit}
</span>
))}
</span>
);
}

View file

@ -107,6 +107,16 @@ export interface NpcDialogueEffect {
* then, and `{{countdown:key}}` tokens tick down to it.
*/
flagDelayMinutes?: number;
/**
* Flag effects only: which player the flag belongs to. `self` (the default)
* targets the active conversation participant; `global` targets the shared
* `user: null` flag of the same key; `user` targets a specific player via
* `flagTargetUserId`. A flag's identity is (owner, key), so the same key can
* hold independent values for different owners.
*/
flagTarget?: "self" | "global" | "user";
/** `flagTarget === "user"`: the player the flag belongs to. */
flagTargetUserId?: number | null;
}
export type DialogueNodeData = {
@ -229,6 +239,29 @@ export function deriveEdges(nodes: DialogueNode[]): DialogueEdge[] {
return edges;
}
/**
* Removes the hop an edge represents from a node's data. Edges are a derived
* projection, so deleting one scrubs the source hop: a choice row (`c0`..`cN`),
* a condition branch (`true`/`false`), or the single continuation. Returns a
* new node and never mutates the input.
*/
export function removeHopFromNode(node: DialogueNode, sourceHandle?: string | null): DialogueNode {
if (node.type === "choice") {
const m = sourceHandle?.match(/^c(\d+)$/);
if (!m) return node;
const idx = Number(m[1]);
const choices = [...(node.data.choices ?? [])];
choices.splice(idx, 1);
return { ...node, data: { ...node.data, choices } };
}
if (node.type === "condition") {
if (sourceHandle === "true") return { ...node, data: { ...node.data, trueTarget: undefined } };
if (sourceHandle === "false") return { ...node, data: { ...node.data, falseTarget: undefined } };
return node;
}
return { ...node, data: { ...node.data, next: undefined } };
}
export interface GraphValidation {
valid: boolean;
errors: string[];
@ -263,6 +296,14 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
if (node.type === "choice" && hop.condition && !hop.condition.key.trim()) {
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
}
if (
node.type === "event" &&
node.data.effect?.type === "flag" &&
node.data.effect.flagTarget === "user" &&
!node.data.effect.flagTargetUserId
) {
errors.push(`An event flag on "${node.id}" set to "Specific user" needs a target player.`);
}
}
}

View file

@ -5,7 +5,30 @@
*/
import type { Payload } from "payload";
import type { DialogueCondition } from "./dialogue";
import type { DialogueCondition, DialogueFlagOp } from "./dialogue";
/**
* Resolve who a flag effect targets. `global` -> null (the shared flag);
* `user` -> the chosen player id, falling back to `selfUserId` when none was
* set, so a misconfigured effect never nudges the global flag by accident;
* `self`/default -> the active conversation participant. The return value is
* exactly the `player-flags.user` column to query and write.
*/
export function resolveFlagOwner(
target: "self" | "global" | "user" | undefined,
targetUserId: number | null | undefined,
selfUserId: number,
): number | null {
switch (target) {
case "global":
return null;
case "user":
return targetUserId ?? selfUserId;
case "self":
default:
return selfUserId;
}
}
/** Effective value of a flag for reading + interpolation. */
export interface FlagValues {
@ -146,3 +169,114 @@ export async function evaluateCondition(
return flag.num === amount;
}
}
/**
* Create-or-update a player flag for `owner` according to the effect's write
* mode. `owner` is a user id (the active participant or a targeted player) or
* null for the shared global flag. A positive `delayMinutes` stamps a future
* `activatesAt`, so the flag reads as false until then (conditions fail,
* countdowns tick toward it). This is the single write path shared by the
* dialogue runtime and its tests, so flag semantics never drift.
*/
export async function applyFlagEffect(
payload: Payload,
owner: number | null,
key: string,
op: DialogueFlagOp,
amount: number,
effectText?: string,
delayMinutes?: number,
): Promise<void> {
const activatesAt =
delayMinutes && delayMinutes > 0
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
: null;
const existing = await payload.find({
collection: "player-flags",
where: { user: { equals: owner }, key: { equals: key } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const doc = existing.docs[0];
if (op === "set_true" || op === "set_false") {
const boolValue = op === "set_true";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_number") {
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_text") {
const textValue = effectText ?? "";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
}
return;
}
// add: numeric flags accumulate; boolean flags convert (true = 1).
const current = doc
? doc.flagType === "number"
? doc.numberValue ?? 0
: doc.boolValue
? 1
: 0
: 0;
const numberValue = current + amount;
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "number", numberValue, activatesAt },
overrideAccess: true,
});
}
}

View file

@ -0,0 +1,19 @@
import type { DialogueNext } from "./dialogue";
/**
* Return a new choices array with the choice at `index` swapped with its
* neighbour in `direction` (-1 = up, +1 = down). Returns `null` when the
* choice is already at an edge and cannot move, so callers can disable the
* corresponding button. The input array is never mutated.
*/
export function reorderChoice(
choices: DialogueNext[],
index: number,
direction: -1 | 1,
): DialogueNext[] | null {
const target = index + direction;
if (target < 0 || target >= choices.length) return null;
const ordered = [...choices];
[ordered[index], ordered[target]] = [ordered[target], ordered[index]];
return ordered;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,530 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Backfill for the MCP plugin's per-collection capability columns on
* payload_mcp_api_keys. The plugin generates one checkbox column per enabled
* collection (<slug>_find/_create/_update/_delete), but only the most recent
* feature migrations added theirs; every older collection was missing its
* columns, so ANY query against the keys table failed with
* 'column ... does not exist' and no API key could ever be listed or created.
* Idempotent (IF NOT EXISTS / IF EXISTS).
*/
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_commands_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_commands_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_commands_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_commands_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_sync_events_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_sync_events_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_sync_events_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "arma_sync_events_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assets_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assets_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assets_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assets_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignment_transfers_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignment_transfers_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignment_transfers_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignment_transfers_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignments_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignments_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignments_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "assignments_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "awards_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "awards_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "awards_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "awards_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_accounts_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_accounts_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_accounts_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_accounts_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_transactions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_transactions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_transactions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "bank_transactions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "campaigns_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "campaigns_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "campaigns_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "campaigns_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefield_scores_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefield_scores_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefield_scores_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefield_scores_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefields_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefields_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefields_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_minefields_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_test_scores_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_test_scores_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_test_scores_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_test_scores_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_tests_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_tests_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_tests_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "custom_radio_tests_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "evaluations_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "evaluations_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "evaluations_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "evaluations_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "experience_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "experience_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "experience_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "experience_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "factions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "factions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "factions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "factions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "form_submissions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "form_submissions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "form_submissions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "form_submissions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "forms_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "forms_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "forms_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "forms_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_event_logs_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_event_logs_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_event_logs_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_event_logs_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_hard_resources_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_hard_resources_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_hard_resources_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_hard_resources_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_npcs_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_npcs_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_npcs_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_npcs_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_servers_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_servers_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_servers_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_servers_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_structures_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_structures_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_structures_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_structures_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_vehicles_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_vehicles_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_vehicles_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "game_vehicles_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labels_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labels_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labels_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labels_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labor_classifications_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labor_classifications_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labor_classifications_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "labor_classifications_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ledger_entries_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ledger_entries_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ledger_entries_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ledger_entries_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "loadouts_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "loadouts_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "loadouts_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "loadouts_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "locker_storages_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "locker_storages_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "locker_storages_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "locker_storages_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "maps_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "maps_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "maps_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "maps_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_listings_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_listings_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_listings_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_listings_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_negotiations_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_negotiations_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_negotiations_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_negotiations_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_state_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_state_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_state_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "market_state_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "media_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "media_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "media_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "media_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_attendances_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_attendances_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_attendances_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_attendances_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_files_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_files_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_files_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mission_files_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "missions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "missions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "missions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "missions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mod_lists_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mod_lists_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mod_lists_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "mod_lists_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "narrative_events_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "narrative_events_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "narrative_events_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "narrative_events_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "npc_staffing_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "npc_staffing_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "npc_staffing_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "npc_staffing_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "plugin_ai_instructions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "plugin_ai_instructions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "plugin_ai_instructions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "plugin_ai_instructions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "profiles_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "profiles_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "profiles_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "profiles_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "projects_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "projects_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "projects_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "projects_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "qualifications_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "qualifications_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "qualifications_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "qualifications_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ranks_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ranks_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ranks_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ranks_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "releases_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "releases_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "releases_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "releases_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "resources_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "resources_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "resources_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "resources_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "roles_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "roles_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "roles_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "roles_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "shipments_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "shipments_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "shipments_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "shipments_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "sprints_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "sprints_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "sprints_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "sprints_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beat_states_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beat_states_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beat_states_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beat_states_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beats_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beats_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beats_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "story_beats_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "structures_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "structures_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "structures_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "structures_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "technologies_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "technologies_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "technologies_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "technologies_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ticket_votes_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ticket_votes_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ticket_votes_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "ticket_votes_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "tickets_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "tickets_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "tickets_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "tickets_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "user_notifications_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "user_notifications_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "user_notifications_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "user_notifications_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "users_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "users_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "users_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "users_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "vehicles_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "vehicles_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "vehicles_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "vehicles_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_scripts_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_scripts_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_scripts_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_scripts_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_submissions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_submissions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_submissions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "voice_submissions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_pages_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_pages_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_pages_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_pages_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_revisions_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_revisions_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_revisions_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_revisions_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_templates_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_templates_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_templates_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN IF NOT EXISTS "wiki_templates_update" boolean DEFAULT false;`) // 256 columns
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_commands_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_commands_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_commands_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_commands_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_sync_events_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_sync_events_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_sync_events_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "arma_sync_events_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assets_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assets_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assets_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assets_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignment_transfers_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignment_transfers_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignment_transfers_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignment_transfers_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignments_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignments_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignments_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "assignments_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "awards_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "awards_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "awards_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "awards_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_accounts_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_accounts_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_accounts_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_accounts_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_transactions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_transactions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_transactions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "bank_transactions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "campaigns_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "campaigns_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "campaigns_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "campaigns_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefield_scores_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefield_scores_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefield_scores_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefield_scores_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefields_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefields_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefields_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_minefields_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_test_scores_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_test_scores_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_test_scores_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_test_scores_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_tests_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_tests_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_tests_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "custom_radio_tests_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "evaluations_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "evaluations_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "evaluations_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "evaluations_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "experience_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "experience_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "experience_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "experience_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "factions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "factions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "factions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "factions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "form_submissions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "form_submissions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "form_submissions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "form_submissions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "forms_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "forms_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "forms_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "forms_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_event_logs_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_event_logs_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_event_logs_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_event_logs_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_hard_resources_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_hard_resources_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_hard_resources_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_hard_resources_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_npcs_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_npcs_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_npcs_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_npcs_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_servers_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_servers_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_servers_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_servers_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_structures_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_structures_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_structures_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_structures_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_vehicles_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_vehicles_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_vehicles_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "game_vehicles_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labels_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labels_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labels_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labels_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labor_classifications_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labor_classifications_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labor_classifications_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "labor_classifications_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ledger_entries_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ledger_entries_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ledger_entries_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ledger_entries_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "loadouts_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "loadouts_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "loadouts_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "loadouts_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "locker_storages_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "locker_storages_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "locker_storages_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "locker_storages_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "maps_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "maps_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "maps_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "maps_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_listings_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_listings_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_listings_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_listings_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_negotiations_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_negotiations_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_negotiations_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_negotiations_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_state_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_state_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_state_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "market_state_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "media_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "media_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "media_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "media_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_attendances_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_attendances_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_attendances_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_attendances_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_files_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_files_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_files_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mission_files_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "missions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "missions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "missions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "missions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mod_lists_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mod_lists_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mod_lists_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "mod_lists_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "narrative_events_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "narrative_events_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "narrative_events_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "narrative_events_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_staffing_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_staffing_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_staffing_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "npc_staffing_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "plugin_ai_instructions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "plugin_ai_instructions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "plugin_ai_instructions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "plugin_ai_instructions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "profiles_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "profiles_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "profiles_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "profiles_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "projects_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "projects_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "projects_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "projects_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "qualifications_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "qualifications_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "qualifications_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "qualifications_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ranks_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ranks_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ranks_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ranks_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "releases_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "releases_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "releases_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "releases_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "resources_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "resources_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "resources_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "resources_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "roles_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "roles_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "roles_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "roles_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "shipments_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "shipments_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "shipments_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "shipments_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "sprints_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "sprints_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "sprints_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "sprints_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beat_states_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beat_states_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beat_states_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beat_states_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beats_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beats_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beats_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "story_beats_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "structures_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "structures_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "structures_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "structures_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "technologies_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "technologies_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "technologies_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "technologies_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ticket_votes_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ticket_votes_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ticket_votes_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "ticket_votes_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "tickets_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "tickets_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "tickets_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "tickets_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "user_notifications_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "user_notifications_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "user_notifications_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "user_notifications_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "users_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "users_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "users_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "users_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "vehicles_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "vehicles_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "vehicles_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "vehicles_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_scripts_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_scripts_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_scripts_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_scripts_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_submissions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_submissions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_submissions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "voice_submissions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_pages_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_pages_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_pages_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_pages_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_revisions_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_revisions_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_revisions_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_revisions_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_templates_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_templates_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_templates_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN IF EXISTS "wiki_templates_update";`)
}

View file

@ -115,6 +115,7 @@ import * as migration_20261006_205845_add_flag_time_windows from './20261006_205
import * as migration_20261007_025942_add_event_log_visibility from './20261007_025942_add_event_log_visibility';
import * as migration_20261007_040914_add_reinforcement_pools from './20261007_040914_add_reinforcement_pools';
import * as migration_20261007_044017_add_ticket_archival from './20261007_044017_add_ticket_archival';
import * as migration_20261007_183000_add_missing_mcp_key_capabilities from './20261007_183000_add_missing_mcp_key_capabilities';
export const migrations = [
{
@ -702,4 +703,9 @@ export const migrations = [
down: migration_20261007_044017_add_ticket_archival.down,
name: '20261007_044017_add_ticket_archival'
},
{
up: migration_20261007_183000_add_missing_mcp_key_capabilities.up,
down: migration_20261007_183000_add_missing_mcp_key_capabilities.down,
name: '20261007_183000_add_missing_mcp_key_capabilities',
},
];

View file

@ -92,7 +92,7 @@ import { CustomRadioTestScores } from "@/collections/minigames/CustomRadioTestSc
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
import { PromotionNominations } from "@/collections/users/PromotionNominations";
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
import hasRoles from "@/utils/access-control/hasRoles";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { scopedAdminPageAccess } from "@/utils/access-control/divisionAccess";
import { payloadAiPlugin, PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
import type { SeedPromptFunction } from "@ai-stack/payloadcms/types";
@ -101,7 +101,6 @@ import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
import { createOpenAI } from "@ai-sdk/openai";
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
import type { User } from "@/payload-types";
// Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
// apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
@ -509,18 +508,22 @@ export default buildConfig({
// storage-adapter-placeholder
mcpPlugin({
collections: mcpCollections,
// MCP API keys let a client act as their user, so issuing them is a
// superuser-tier operation: `system:admin-access` passes for dynamic
// superusers (hasPermission bypass) and for roles explicitly holding it.
// The legacy `hasRoles` enum check this replaced read only the old
// `roles` column, which every current admin user lacks, so nobody could
// create or see keys and no MCP client could authenticate. Admin-panel
// visibility follows the read gate (the repo's requireAdminPageAccess
// pattern); `admin.hidden` is sync-only and cannot run permission lookups.
overrideApiKeyCollection: (collection) => ({
...collection,
admin: {
...collection.admin,
hidden: ({ user }) => !hasRoles(["admin", "developer"], user as User),
},
access: {
...collection.access,
read: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
update: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
create: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
delete: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
read: requirePermission("system:admin-access"),
update: requirePermission("system:admin-access"),
create: requirePermission("system:admin-access"),
delete: requirePermission("system:admin-access"),
},
}),
}),
@ -589,15 +592,14 @@ export default buildConfig({
[Labels.slug]: true,
},
debugging: true,
// Same superuser-tier gate as the MCP API keys above; the AI plugin's
// instructions collection is admin-only tooling.
overrideInstructions: {
admin: {
hidden: ({ user }) => !hasRoles(["admin", "developer"], user as User),
},
access: {
read: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
update: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
create: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
delete: ({ req }) => hasRoles(["admin", "developer"], req.user as User),
read: requirePermission("system:admin-access"),
update: requirePermission("system:admin-access"),
create: requirePermission("system:admin-access"),
delete: requirePermission("system:admin-access"),
},
},
generationModels: [

View file

@ -0,0 +1,318 @@
// @vitest-environment node
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
// the global Uint8Array come from different realms, so signing throws a TypeError.
import { getFieldsToSign, getPayload, jwtSign, type CollectionSlug, type Payload, type Where } from "payload";
import config from "@/payload.config";
import { randomUUID } from "node:crypto";
import { NextRequest } from "next/server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, Structure, User } from "@/payload-types";
import { POST } from "@/app/api/game-structures/set-labor-headcount/route";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
const RUN = `lcr-${Date.now().toString(36)}`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "", format: "", type: "text", version: 1 }],
direction: null,
format: "",
indent: 0,
version: 1,
},
};
const TIMEOUT = 30_000;
/** Build a NextRequest against the admin route, optionally authenticated + bodied. */
function request(token?: string, body?: unknown): NextRequest {
const headers = new Headers();
if (token) headers.set("cookie", `payload-token=${token}`);
return new NextRequest(
"http://localhost/api/game-structures/set-labor-headcount",
{
headers,
method: "POST",
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
},
);
}
/**
* Mint a payload-token JWT for a user, mirroring the impersonation route:
* persist a session on the user doc, then sign with that session's sid.
*/
async function mintToken(userId: number): Promise<string> {
const collection = payload.collections.users.config;
const user = await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
});
const sid = randomUUID();
const now = new Date();
const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000);
const sessions = (user.sessions ?? []).filter(
(session) => new Date(session.expiresAt).getTime() > now.getTime(),
);
sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() });
await payload.update({
collection: "users",
id: userId,
data: { sessions },
overrideAccess: true,
});
const { token } = await jwtSign({
fieldsToSign: getFieldsToSign({
collectionConfig: collection,
email: user.email ?? "",
sid,
user,
}),
secret: payload.secret,
tokenExpiration: collection.auth.tokenExpiration,
});
return token;
}
async function sweep(collection: CollectionSlug, where: Where) {
const found = await payload.find({
collection,
where,
limit: 200,
depth: 0,
overrideAccess: true,
});
await Promise.allSettled(
found.docs.map((doc) =>
payload.delete({ collection, id: doc.id as number, overrideAccess: true }),
),
);
}
describe("game-structures set-labor-headcount admin route", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const blueprintIds: number[] = [];
const classificationIds: number[] = [];
const mapIds: number[] = [];
let superUserId: number;
let plainUserId: number;
let superUserToken: string;
let plainUserToken: string;
let siteId: number;
let classificationId: number;
let hiringWasEnabled = false;
beforeAll(async () => {
payload = await getPayload({ config: await config });
invalidatePermissionCache();
// enable staffing so setLaborHeadcount does not fail closed.
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
hiringWasEnabled = Boolean(rules.staffHiringEnabled);
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: true },
overrideAccess: true,
depth: 0,
});
// A map to seat the structure on (not required, but mirrors real placement).
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
overrideAccess: true,
depth: 0,
})) as { id: number };
mapIds.push(map.id);
// A classification with plenty of available workers.
const classification = (await payload.create({
collection: "labor-classifications",
data: { name: `${RUN} Labor`, key: `${RUN}-labor`, defaultUnitSalary: 5, availableHeadcount: 50 },
overrideAccess: true,
depth: 0,
})) as { id: number };
classificationIds.push(classification.id);
classificationId = classification.id;
// A resource so the blueprint can carry required materials.
const materialResource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Material`,
codeName: `${RUN}-material`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
})) as { id: number };
// A blueprint that requires the classification (laborRequirements is copied into
// the game-structure on create by the beforeChange hook).
const blueprint = (await payload.create({
collection: "structures",
data: {
name: `${RUN} Site`,
codeName: `${RUN}-site`,
approvalStatus: "in_progress",
category: "logistics",
materials: [{ resource: materialResource.id, amount: 1 }],
constructionDurationMinutes: 10,
constructionCrewRequired: 1,
terrainType: "land",
maxHealth: 100,
description: LEXICAL_EMPTY as unknown as Structure["description"],
laborRequirements: [
{ classification: classification.id, requiredHeadcount: 2, maxHeadcount: 6 },
],
},
overrideAccess: true,
depth: 0,
})) as { id: number };
blueprintIds.push(blueprint.id);
const site = (await payload.create({
collection: "game-structures",
data: { name: `${RUN} Site`, type: blueprint.id, map: map.id, coordinates: [500, 500] },
overrideAccess: true,
depth: 0,
})) as { id: number };
siteId = site.id;
// Superuser role + user (passes game-structures:update via the superuser bypass).
const superRole = (await payload.create({
collection: "roles",
data: { name: `${RUN} Labor Admin`, slug: `${RUN}-labor-admin`, isSuperuser: true },
overrideAccess: true,
depth: 0,
})) as { id: number };
roleIds.push(superRole.id);
const superUser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-su`,
discordUsername: `${RUN}-su`,
displayName: "SU",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
// Permission resolution reads roleDocs (dynamic RBAC), not the legacy enum.
roleDocs: [superRole.id],
},
overrideAccess: true,
depth: 0,
})) as User;
userIds.push(superUser.id);
superUserId = superUser.id;
// Plain (no-permission) role + user.
const plainRole = (await payload.create({
collection: "roles",
data: { name: `${RUN} Plain`, slug: `${RUN}-plain`, permissions: [] },
overrideAccess: true,
depth: 0,
})) as { id: number };
roleIds.push(plainRole.id);
const plainUser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-plain`,
discordUsername: `${RUN}-plain`,
displayName: "Plain",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [plainRole.id],
},
overrideAccess: true,
depth: 0,
})) as User;
userIds.push(plainUser.id);
plainUserId = plainUser.id;
superUserToken = await mintToken(superUserId);
plainUserToken = await mintToken(plainUserId);
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
// FK-safe order, best-effort (the test DB is truncated between runs regardless).
if (typeof siteId === "number") {
await sweep("npc-staffing", { structure: { equals: siteId } });
}
await sweep("game-structures", { name: { like: `${RUN}%` } });
await sweep("structures", { name: { like: `${RUN}%` } });
await sweep("labor-classifications", { name: { like: `${RUN}%` } });
await sweep("maps", { name: { like: `${RUN}%` } });
for (const id of userIds) {
await sweep("profiles", { user: { equals: id } });
await Promise.allSettled([payload.delete({ collection: "users", id, overrideAccess: true })]);
}
for (const id of roleIds) {
await Promise.allSettled([payload.delete({ collection: "roles", id, overrideAccess: true })]);
}
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: hiringWasEnabled },
overrideAccess: true,
depth: 0,
});
}, TIMEOUT);
it("rejects unauthenticated requests with 401", async () => {
const res = await POST(request());
expect(res.status).toBe(401);
}, TIMEOUT);
it("rejects an authenticated non-staff user with 403", async () => {
const res = await POST(request(plainUserToken));
expect(res.status).toBe(403);
}, TIMEOUT);
it("rejects a malformed body with 400", async () => {
const res = await POST(request(superUserToken, { classificationId }));
expect(res.status).toBe(400);
}, TIMEOUT);
it("sets the crew headcount for a valid request", async () => {
const res = await POST(
request(superUserToken, { structureId: siteId, classificationId, headcount: 3, unitSalary: 5 }),
);
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({ success: true });
const staffing = await payload.find({
collection: "npc-staffing",
where: {
structure: { equals: siteId },
laborClassification: { equals: classificationId },
positionType: { equals: "labor" },
},
overrideAccess: true,
depth: 0,
});
const active = staffing.docs.find((doc) => doc.status === "active");
expect(active?.headcount).toBe(3);
}, TIMEOUT);
it("rejects a headcount over the blueprint cap with 400", async () => {
const res = await POST(
request(superUserToken, { structureId: siteId, classificationId, headcount: 999, unitSalary: 5 }),
);
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ success: false });
}, TIMEOUT);
});

View file

@ -0,0 +1,180 @@
import crypto from "crypto";
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, User } from "@/payload-types";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
const RUN = `mcpkeys-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
/**
* The MCP plugin exposes its API-key collection (`payload-mcp-api-keys`) to
* every logged-in user by default ("manage only their OWN keys"). The app's
* override restricts it to the superuser tier via `requirePermission
* ("system:admin-access")`. An earlier override used the legacy `hasRoles`
* enum check, which no current admin user satisfies, so NOBODY could create
* keys and no MCP client could authenticate (the endpoint 401'd for everyone).
*/
describe("MCP API key collection access (payload-mcp-api-keys)", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const keyIds: number[] = [];
let plainUser: User;
let superUser: User;
let scopedAdminUser: User;
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
invalidatePermissionCache();
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
invalidatePermissionCache();
return user;
};
beforeAll(async () => {
payload = await getPayload({ config });
const plainRole = await makeRole("plain");
const superRole = await makeRole("super", { isSuperuser: true });
const scopedRole = await makeRole("scoped", { permissions: ["system:admin-access"] });
plainUser = await makeUser("plain", plainRole.id);
superUser = await makeUser("super", superRole.id);
scopedAdminUser = await makeUser("scoped", scopedRole.id);
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
for (const id of keyIds) {
await payload
.delete({ collection: "payload-mcp-api-keys", id, overrideAccess: true })
.catch(() => {});
}
for (const id of userIds) {
// User creation auto-creates a Profile; its user_id is NOT NULL, so it
// must go before the user (the repo's other specs do the same).
const profiles = await payload
.find({ collection: "profiles", where: { user: { equals: id } }, overrideAccess: true })
.catch(() => ({ docs: [] as { id: number | string }[] }));
for (const p of profiles.docs) {
await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
invalidatePermissionCache();
}, TIMEOUT);
it(
"rejects key creation by regular users",
async () => {
await expect(
payload.create({
collection: "payload-mcp-api-keys",
data: { label: `${RUN}-nope`, enableAPIKey: true, user: plainUser.id },
user: plainUser,
overrideAccess: false,
}),
).rejects.toThrow();
},
TIMEOUT,
);
it(
"lets a dynamic superuser create a key that resolves like the MCP endpoint does",
async () => {
// Payload stores whatever plaintext key the creator supplies (the admin
// panel's Generate button does the same via the auth route); the plugin
// authenticates by HMAC-SHA256-indexing it with the Payload secret.
const rawKey = `${RUN}-${crypto.randomBytes(24).toString("hex")}`;
const key = await payload.create({
collection: "payload-mcp-api-keys",
data: { label: `${RUN}-super`, enableAPIKey: true, apiKey: rawKey, user: superUser.id },
user: superUser,
overrideAccess: false,
});
keyIds.push(key.id as number);
expect((key as unknown as Record<string, unknown>).apiKey).toBe(rawKey);
const apiKeyIndex = crypto
.createHmac("sha256", payload.secret)
.update(rawKey)
.digest("hex");
const { docs } = await payload.find({
collection: "payload-mcp-api-keys",
where: { apiKeyIndex: { equals: apiKeyIndex } },
depth: 1,
limit: 1,
pagination: false,
overrideAccess: true,
});
expect(docs).toHaveLength(1);
const owner = docs[0].user as unknown as User | number;
expect(typeof owner === "object" ? owner.id : owner).toBe(superUser.id);
},
TIMEOUT,
);
it(
"lets a role explicitly granted system:admin-access create keys too",
async () => {
const key = await payload.create({
collection: "payload-mcp-api-keys",
data: { label: `${RUN}-scoped`, enableAPIKey: true, user: scopedAdminUser.id },
user: scopedAdminUser,
overrideAccess: false,
});
keyIds.push(key.id as number);
expect(key.id).toBeDefined();
},
TIMEOUT,
);
it(
"hides existing keys from regular users",
async () => {
// The gate returns a boolean false for non-superusers, so Payload
// rejects the query outright rather than filtering to an empty list.
await expect(
payload.find({
collection: "payload-mcp-api-keys",
user: plainUser,
overrideAccess: false,
}),
).rejects.toThrow();
},
TIMEOUT,
);
});

View file

@ -0,0 +1,121 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { applyFlagEffect, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
let payload: Payload;
const RUN = `dlg_target_${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const userIds: number[] = [];
/** Minimal playable user so the player-flags user FK resolves. */
async function createUser(username: string): Promise<{ id: number }> {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `TARGET ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
userIds.push(user.id);
return user;
}
describe("flag owner targeting (event node effects)", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
const flags = await payload.find({
collection: "player-flags",
where: { key: { like: `${RUN}_%` } },
limit: 200,
overrideAccess: true,
});
for (const doc of flags.docs) {
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
});
it("resolves the owner column from the effect scope", () => {
const participant = 42;
expect(resolveFlagOwner(undefined, undefined, participant)).toBe(participant);
expect(resolveFlagOwner("self", undefined, participant)).toBe(participant);
expect(resolveFlagOwner("global", undefined, participant)).toBeNull();
expect(resolveFlagOwner("user", 7, participant)).toBe(7);
// A "user" target with no id falls back to the participant so a
// misconfigured effect never nudges the global flag by accident.
expect(resolveFlagOwner("user", undefined, participant)).toBe(participant);
expect(resolveFlagOwner("user", null, participant)).toBe(participant);
});
it("writes the self flag for the active participant", async () => {
const participant = await createUser(`${RUN}_self_player`);
await applyFlagEffect(payload, participant.id, `${RUN}_self`, "set_true", 0);
const res = await payload.find({
collection: "player-flags",
where: { user: { equals: participant.id }, key: { equals: `${RUN}_self` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs).toHaveLength(1);
expect(res.docs[0].flagType).toBe("boolean");
expect(res.docs[0].boolValue).toBe(true);
});
it("writes the global flag (owner null) under the shared key", async () => {
await applyFlagEffect(payload, null, `${RUN}_global`, "set_number", 5);
const res = await payload.find({
collection: "player-flags",
where: { user: { equals: null }, key: { equals: `${RUN}_global` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs).toHaveLength(1);
expect(res.docs[0].flagType).toBe("number");
expect(res.docs[0].numberValue).toBe(5);
});
it("writes a targeted user's flag independently of the participant and the key", async () => {
const target = await createUser(`${RUN}_target_player`);
const participant = await createUser(`${RUN}_participant`);
// Same key, different owner: the participant gets nothing.
await applyFlagEffect(payload, target.id, `${RUN}_shared`, "set_text", 0, "{green}OK{/}");
const forTarget = await payload.find({
collection: "player-flags",
where: { user: { equals: target.id }, key: { equals: `${RUN}_shared` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(forTarget.docs).toHaveLength(1);
expect(forTarget.docs[0].flagType).toBe("text");
expect(forTarget.docs[0].textValue).toBe("{green}OK{/}");
const forParticipant = await payload.find({
collection: "player-flags",
where: { user: { equals: participant.id }, key: { equals: `${RUN}_shared` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(forParticipant.docs).toHaveLength(0);
});
});

View file

@ -394,6 +394,11 @@ describe("markup accumulation + links + countdowns", () => {
const empty = render("x{cd|}y");
expect(empty).toContain("xy");
expect(empty).not.toContain("cd|");
// Each unit is its own inline-flex cell (CSS gap) so the gap between units
// is controlled instead of the raw monospace space reading wide/odd inline.
const html = render(`{cd|${future}}`);
expect(html).toContain("inline-flex");
expect(html.match(/whitespace-nowrap/g)?.length).toBe(2);
});
it("formats remaining time compactly", () => {

View file

@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { removeHopFromNode } from "@/lib/npc-dialogue/dialogue";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
const node = (type: DialogueNode["type"], data: DialogueNode["data"]): DialogueNode => ({
id: `${type}-1`,
type,
position: { x: 0, y: 0 },
data,
});
describe("removeHopFromNode (edge deletion scrubs the derived hop)", () => {
it("removes a single choice row by its handle", () => {
const n = node("choice", { choices: [{ label: "a", target: "x" }, { label: "b", target: "y" }] });
const next = removeHopFromNode(n, "c0");
expect(next.data.choices).toEqual([{ label: "b", target: "y" }]);
// the other row is untouched
expect(n.data.choices).toEqual([
{ label: "a", target: "x" },
{ label: "b", target: "y" },
]);
});
it("removes a condition branch by name", () => {
const yes = node("condition", { condition: { kind: "flag", key: "k", op: "is_true" }, trueTarget: "t", falseTarget: "f" });
expect(removeHopFromNode(yes, "true").data.trueTarget).toBeUndefined();
expect(removeHopFromNode(yes, "true").data.falseTarget).toBe("f");
const no = node("condition", { condition: { kind: "flag", key: "k", op: "is_true" }, trueTarget: "t", falseTarget: "f" });
const falseRemoved = removeHopFromNode(no, "false");
expect(falseRemoved.data.falseTarget).toBeUndefined();
expect(falseRemoved.data.trueTarget).toBe("t");
});
it("clears the single continuation on a plain node", () => {
const n = node("dialogue", { body: "hi", next: { label: "next", target: "t" } });
expect(removeHopFromNode(n).data.next).toBeUndefined();
});
it("leaves a choice node unchanged when the handle is not a numbered row", () => {
const n = node("choice", { choices: [{ label: "a", target: "x" }] });
expect(removeHopFromNode(n, undefined)).toEqual(n);
});
});

View file

@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import type { DialogueNext } from "@/lib/npc-dialogue/dialogue";
/** Build a choice with a unique target so reordering is observable. */
const choice = (label: string): DialogueNext => ({ label, target: `node-${label}` });
describe("reorderChoice (editor choice ordering)", () => {
const choices = [choice("a"), choice("b"), choice("c")];
it("swaps a choice with its neighbour", () => {
expect(reorderChoice(choices, 0, 1)).toEqual([choice("b"), choice("a"), choice("c")]);
// direction -1 from index 1 lands on the same swap
expect(reorderChoice(choices, 1, -1)).toEqual([choice("b"), choice("a"), choice("c")]);
expect(reorderChoice(choices, 2, -1)).toEqual([choice("a"), choice("c"), choice("b")]);
});
it("returns null at the edges so nothing moves", () => {
expect(reorderChoice(choices, 0, -1)).toBeNull();
expect(reorderChoice(choices, 2, 1)).toBeNull();
// A single-item list is an edge in every direction.
expect(reorderChoice([choice("only")], 0, 1)).toBeNull();
expect(reorderChoice([choice("only")], 0, -1)).toBeNull();
});
it("does not mutate the input array", () => {
const moved = reorderChoice(choices, 1, 1);
expect(moved).not.toBe(choices);
expect(choices).toEqual([choice("a"), choice("b"), choice("c")]);
});
});