1
0
Fork 0

feat(npc-dialogue): entry gates and priority for multi-conversation selection

- npc-dialogues gains priority + entryGate (flag key/op/amount) fields
- contact page offers the highest-priority conversation whose gate
  passes (ungated = fallback, ties by oldest); only the winner's flow
  leaves the server so locked story content never reaches clients
- extract shared flag reads (readFlag/evaluateCondition) to
  lib/npc-dialogue/flags and pure selection to lib/npc-dialogue/selection
- migration 20261006_203217_add_dialogue_entry_gate; spec covers
  ordering, gating, fallback, and storage round-trip
This commit is contained in:
Jason Fraley 2026-10-06 16:42:56 -04:00
parent 43cf29c6f4
commit c1e13e5dc9
11 changed files with 37807 additions and 98 deletions

View file

@ -9,12 +9,8 @@ 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 type {
DialogueCondition,
DialogueFlagOp,
FlowData,
NpcDialogueEffect,
} from "@/lib/npc-dialogue/dialogue";
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
import type { DialogueFlagOp, FlowData, NpcDialogueEffect } from "@/lib/npc-dialogue/dialogue";
interface ActionResult<T = undefined> {
success: boolean;
@ -140,66 +136,6 @@ async function runEffect(
}
}
/**
* Effective value of a flag: player-specific entry takes priority; if absent,
* fall back to the global entry (user is null). Missing flags read false / 0 /
* empty. `text` is the string the flag contributes to interpolated dialogue
* (booleans render "true"/"false", numbers their digits, text flags verbatim).
*/
async function readFlag(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,
key: string,
): Promise<{ bool: boolean; num: number; text: string }> {
// Player-specific flag (priority).
const playerRes = await payload.find({
collection: "player-flags",
where: {
user: { equals: userId },
key: { equals: key },
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const playerDoc = playerRes.docs[0];
if (playerDoc) return flagValues(playerDoc);
// Global fallback (user is null).
const globalRes = await payload.find({
collection: "player-flags",
where: {
user: { equals: null },
key: { equals: key },
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const globalDoc = globalRes.docs[0];
if (!globalDoc) return { bool: false, num: 0, text: "" };
return flagValues(globalDoc);
}
/** Reads a stored flag doc into its condition + interpolation values. */
function flagValues(doc: {
flagType: "boolean" | "number" | "text";
boolValue?: boolean | null;
numberValue?: number | null;
textValue?: string | null;
}): { bool: boolean; num: number; text: string } {
if (doc.flagType === "number") {
const num = doc.numberValue ?? 0;
return { bool: num !== 0, num, text: String(num) };
}
if (doc.flagType === "text") {
const text = doc.textValue ?? "";
return { bool: text.trim().length > 0, num: 0, text };
}
const bool = doc.boolValue === true;
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false" };
}
/** Create-or-update a player flag according to the effect's write mode. */
async function applyFlagEffect(
payload: Awaited<ReturnType<typeof getPayload>>,
@ -427,28 +363,3 @@ export async function resolveNpcDialogueTexts(
}
}
async function evaluateCondition(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,
condition: DialogueCondition,
): Promise<boolean> {
const flag = await readFlag(payload, userId, condition.key);
const amount = condition.amount ?? 0;
switch (condition.op) {
case "is_true":
return flag.bool;
case "is_false":
return !flag.bool;
case "gte":
return flag.num >= amount;
case "lte":
return flag.num <= amount;
case "gt":
return flag.num > amount;
case "lt":
return flag.num < amount;
case "eq":
return flag.num === amount;
}
}

View file

@ -4,6 +4,8 @@ import { notFound } from "next/navigation";
import { headers as nextHeaders } from "next/headers";
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
@ -153,7 +155,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
const dialogue =
npc.canMessage === true
? await firstDialogue(payload, id)
? await pickDialogue(payload, id, user?.id as number | undefined)
: null;
return (
@ -180,16 +182,29 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
);
}
/** Fetches the single dialogue flowchart for an NPC, if one exists. */
async function firstDialogue(
/**
* Picks the conversation to offer this player: among all of the NPC's
* conversations, the highest-priority one whose entry gate passes (ungated
* always passes). Only the winner's flowchart leaves the server, so gated
* story content never reaches a client that has not unlocked it.
*/
async function pickDialogue(
payload: Awaited<ReturnType<typeof getPayload>>,
npcId: number,
userId: number | undefined,
) {
const res = await payload.find({
collection: "npc-dialogues",
where: { npc: { equals: npcId } },
limit: 1,
limit: 25,
depth: 0,
});
return res.docs[0] as unknown as { id: number; flowData?: FlowData } | null;
if (res.docs.length === 0) return null;
const chosen = await selectDialogueForUser(res.docs, async (condition) => {
if (!userId) return false;
return evaluateCondition(payload, userId, condition);
});
if (!chosen) return null;
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
}

View file

@ -1,5 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
export const NpcDialogues: CollectionConfig = {
slug: "npc-dialogues",
@ -7,7 +8,7 @@ export const NpcDialogues: CollectionConfig = {
group: "Game",
useAsTitle: "name",
listSearchableFields: ["name"],
defaultColumns: ["name", "npc"],
defaultColumns: ["name", "npc", "priority"],
pagination: { defaultLimit: 50 },
},
access: {
@ -38,6 +39,51 @@ export const NpcDialogues: CollectionConfig = {
canMessage: { equals: true },
},
},
{
name: "priority",
type: "number",
defaultValue: 0,
admin: {
description:
"When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.",
},
},
{
name: "entryGate",
type: "group",
admin: {
description:
"Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).",
},
fields: [
{
name: "key",
type: "text",
admin: {
description:
"player-flags key checked for the reading player. Player-specific flag takes priority; falls back to global. Missing = false / 0.",
},
},
{
name: "op",
type: "select",
defaultValue: "is_true",
options: CONDITION_OPS,
admin: {
description: "Comparison applied to the flag's effective value.",
},
},
{
name: "amount",
type: "number",
admin: {
condition: (_data, blockData) =>
["gte", "lte", "gt", "lt", "eq"].includes(String(blockData?.op)),
description: "Right-hand side for the numeric comparisons.",
},
},
],
},
{
type: "tabs",
tabs: [

View file

@ -58,6 +58,17 @@ export interface DialogueCondition {
amount?: number;
}
/** All condition operators, in UI order. */
export const CONDITION_OPS: DialogueCondition["op"][] = [
"is_true",
"is_false",
"gte",
"lte",
"gt",
"lt",
"eq",
];
/** How a flag effect writes the flag. */
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "set_text" | "add";

View file

@ -0,0 +1,101 @@
/**
* Server-side flag reads for NPC conversations. Shared by the conversation
* runtime actions and the contact page's conversation picker so condition
* semantics never drift apart.
*/
import type { Payload } from "payload";
import type { DialogueCondition } from "./dialogue";
/** Effective value of a flag for reading + interpolation. */
export interface FlagValues {
bool: boolean;
num: number;
text: string;
}
/**
* Effective value of a flag: player-specific entry takes priority; if absent,
* fall back to the global entry (user is null). Missing flags read false / 0 /
* empty. `text` is the string the flag contributes to interpolated dialogue
* (booleans render "true"/"false", numbers their digits, text flags verbatim).
*/
export async function readFlag(
payload: Payload,
userId: number,
key: string,
): Promise<FlagValues> {
// Player-specific flag (priority).
const playerRes = await payload.find({
collection: "player-flags",
where: {
user: { equals: userId },
key: { equals: key },
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const playerDoc = playerRes.docs[0];
if (playerDoc) return flagValues(playerDoc);
// Global fallback (user is null).
const globalRes = await payload.find({
collection: "player-flags",
where: {
user: { equals: null },
key: { equals: key },
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const globalDoc = globalRes.docs[0];
if (!globalDoc) return { bool: false, num: 0, text: "" };
return flagValues(globalDoc);
}
/** Reads a stored flag doc into its condition + interpolation values. */
export function flagValues(doc: {
flagType: "boolean" | "number" | "text";
boolValue?: boolean | null;
numberValue?: number | null;
textValue?: string | null;
}): FlagValues {
if (doc.flagType === "number") {
const num = doc.numberValue ?? 0;
return { bool: num !== 0, num, text: String(num) };
}
if (doc.flagType === "text") {
const text = doc.textValue ?? "";
return { bool: text.trim().length > 0, num: 0, text };
}
const bool = doc.boolValue === true;
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false" };
}
/** Evaluates one authored condition against the user's live flags. */
export async function evaluateCondition(
payload: Payload,
userId: number,
condition: DialogueCondition,
): Promise<boolean> {
const flag = await readFlag(payload, userId, condition.key);
const amount = condition.amount ?? 0;
switch (condition.op) {
case "is_true":
return flag.bool;
case "is_false":
return !flag.bool;
case "gte":
return flag.num >= amount;
case "lte":
return flag.num <= amount;
case "gt":
return flag.num > amount;
case "lt":
return flag.num < amount;
case "eq":
return flag.num === amount;
}
}

View file

@ -0,0 +1,53 @@
/**
* Conversation selection when an NPC has multiple conversations.
*
* Each conversation may declare an entry gate (a flag condition evaluated
* against the reading player) and a priority. The offer order is priority
* descending, oldest first; the first conversation whose gate passes wins.
* An empty gate key always passes, which makes ungated conversations the
* natural fallback. Pure module: the caller injects the condition evaluator
* so this stays testable and client-safe.
*/
import type { DialogueCondition } from "./dialogue";
/** The stored entry gate shape on an npc-dialogues document. */
export interface DialogueEntryGate {
key?: string | null;
op?: DialogueCondition["op"] | null;
amount?: number | null;
}
/** Minimal candidate shape the selector reads from a conversation doc. */
export interface GateCandidate {
id: number;
priority?: number | null;
entryGate?: DialogueEntryGate | null;
}
/** Turns a stored gate into a runtime condition; null when ungated. */
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
const key = gate?.key?.trim();
if (!key || !gate) return null;
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
}
/**
* Picks the conversation to offer: highest priority first (ties break by
* oldest id), gated conversations skipped unless `evaluate` passes their
* condition. Returns null when every candidate is gated shut.
*/
export async function selectDialogueForUser<T extends GateCandidate>(
docs: readonly T[],
evaluate: (condition: DialogueCondition) => Promise<boolean>,
): Promise<T | null> {
const ordered = [...docs].sort(
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,
);
for (const doc of ordered) {
const condition = gateCondition(doc.entryGate);
if (!condition) return doc;
if (await evaluate(condition)) return doc;
}
return null;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,19 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_npc_dialogues_entry_gate_op" AS ENUM('is_true', 'is_false', 'gte', 'lte', 'gt', 'lt', 'eq');
ALTER TABLE "npc_dialogues" ADD COLUMN "priority" numeric DEFAULT 0;
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_key" varchar;
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_op" "enum_npc_dialogues_entry_gate_op" DEFAULT 'is_true';
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_amount" numeric;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "npc_dialogues" DROP COLUMN "priority";
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_key";
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_op";
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_amount";
DROP TYPE "public"."enum_npc_dialogues_entry_gate_op";`)
}

View file

@ -110,6 +110,7 @@ import * as migration_20261005_185014_add_player_flags from './20261005_185014_a
import * as migration_20261006_000000_add_npc_dialogue_and_activity_fields from './20261006_000000_add_npc_dialogue_and_activity_fields';
import * as migration_20261006_155244_add_global_flag_support from './20261006_155244_add_global_flag_support';
import * as migration_20261006_195605_add_text_flag_type from './20261006_195605_add_text_flag_type';
import * as migration_20261006_203217_add_dialogue_entry_gate from './20261006_203217_add_dialogue_entry_gate';
export const migrations = [
{
@ -670,6 +671,11 @@ export const migrations = [
{
up: migration_20261006_195605_add_text_flag_type.up,
down: migration_20261006_195605_add_text_flag_type.down,
name: '20261006_195605_add_text_flag_type'
name: '20261006_195605_add_text_flag_type',
},
{
up: migration_20261006_203217_add_dialogue_entry_gate.up,
down: migration_20261006_203217_add_dialogue_entry_gate.down,
name: '20261006_203217_add_dialogue_entry_gate'
},
];

View file

@ -2526,6 +2526,27 @@ export interface NpcDialogue {
* The contact this conversation belongs to.
*/
npc: number | GameNpc;
/**
* When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.
*/
priority?: number | null;
/**
* Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).
*/
entryGate?: {
/**
* player-flags key checked for the reading player. Player-specific flag takes priority; falls back to global. Missing = false / 0.
*/
key?: string | null;
/**
* Comparison applied to the flag's effective value.
*/
op?: ('is_true' | 'is_false' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
/**
* Right-hand side for the numeric comparisons.
*/
amount?: number | null;
};
flowData:
| {
[k: string]: unknown;
@ -7836,6 +7857,14 @@ export interface NpcStaffingSelect<T extends boolean = true> {
export interface NpcDialoguesSelect<T extends boolean = true> {
name?: T;
npc?: T;
priority?: T;
entryGate?:
| T
| {
key?: T;
op?: T;
amount?: T;
};
flowData?: T;
updatedAt?: T;
createdAt?: T;

View file

@ -7,6 +7,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
import {
collectNodeTokens,
extractFlagTokens,
@ -161,6 +162,53 @@ describe("text flags (player-flags collection)", () => {
expect(updated.textValue).toBe("{amber}REDACTED{/}");
expect(formatFlagValue(updated)).toBe("{amber}REDACTED{/}");
});
it("stores conversation priority + entry gate and drives selection", async () => {
const npc = await payload.create({
collection: "game-npcs",
data: { name: `${RUN}_gate_npc`, canMessage: true },
overrideAccess: true,
});
const flow = { nodes: [], edges: [] };
const gated = await payload.create({
collection: "npc-dialogues",
data: {
name: `${RUN}_gated`,
npc: npc.id,
flowData: flow,
priority: 10,
entryGate: { key: `${RUN}_met`, op: "is_true" },
},
overrideAccess: true,
});
const fallback = await payload.create({
collection: "npc-dialogues",
data: { name: `${RUN}_fallback`, npc: npc.id, flowData: flow },
overrideAccess: true,
});
try {
const res = await payload.find({
collection: "npc-dialogues",
where: { npc: { equals: npc.id } },
limit: 10,
depth: 0,
overrideAccess: true,
});
expect(res.docs).toHaveLength(2);
const unlocked = new Set([`${RUN}_met`]);
const chosen = await selectDialogueForUser(res.docs, async (c) => unlocked.has(c.key));
expect(chosen?.id).toBe(gated.id);
const fallen = await selectDialogueForUser(res.docs, async () => false);
expect(fallen?.id).toBe(fallback.id);
} finally {
for (const doc of [gated, fallback]) {
await payload.delete({ collection: "npc-dialogues", id: doc.id, overrideAccess: true });
}
await payload.delete({ collection: "game-npcs", id: npc.id, overrideAccess: true });
}
});
});
describe("inline images in dialogue markup", () => {
@ -189,6 +237,50 @@ describe("inline images in dialogue markup", () => {
});
});
describe("conversation selection (entry gates + priority)", () => {
const pass = async () => true;
const fail = async () => false;
it("prefers higher priority regardless of input order", async () => {
const docs = [
{ id: 1, priority: 0 },
{ id: 2, priority: 10 },
{ id: 3, priority: 5 },
];
expect((await selectDialogueForUser(docs, pass))?.id).toBe(2);
});
it("breaks ties by oldest id", async () => {
const docs = [{ id: 7 }, { id: 3, priority: 0 }];
expect((await selectDialogueForUser(docs, pass))?.id).toBe(3);
});
it("skips gated conversations whose condition fails, falling back to ungated", async () => {
const docs = [
{ id: 1, priority: 10, entryGate: { key: "met_fixer", op: "is_true" as const } },
{ id: 2, priority: 0 },
];
expect((await selectDialogueForUser(docs, fail))?.id).toBe(2);
expect((await selectDialogueForUser(docs, pass))?.id).toBe(1);
});
it("returns null when every candidate is gated shut", async () => {
const docs = [{ id: 1, entryGate: { key: "secret", op: "is_true" as const } }];
expect(await selectDialogueForUser(docs, fail)).toBeNull();
});
it("treats blank gate keys as ungated and defaults the op", () => {
expect(gateCondition({ key: " " })).toBeNull();
expect(gateCondition(null)).toBeNull();
expect(gateCondition({ key: "x" })).toEqual({
kind: "flag",
key: "x",
op: "is_true",
amount: 0,
});
});
});
describe("choice tooltip interpolation", () => {
it("collects tokens from tooltips and resolves them index-aligned", () => {
const node: DialogueNode = {