1
0
Fork 0

feat(npc-dialogue): add defined checks to flag conditions

is_true/is_false test truthiness, so a flag explicitly set to false reads
the same as a flag that was never recorded. is_defined/is_undefined test
existence instead, which lets a branch fire on "has this happened yet".

A pending-activation flag counts as defined (recorded, not yet in effect)
and an expired personal entry now falls through to the global entry, which
is what readFlag's contract already promised.

NUMERIC_CONDITION_OPS becomes the shared list of ops that take an amount, so
the editor, the entryGate field and conditionSummary agree. Adding to
CONDITION_OPS also alters enum_npc_dialogues_entry_gate_op, so the migration
is an ALTER TYPE ADD VALUE, applied to dev.
This commit is contained in:
Jason Fraley 2026-11-24 17:34:40 -05:00
parent 9f8a0d87ea
commit 04bbc66edc
11 changed files with 47284 additions and 14 deletions

View file

@ -1,6 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
import { CONDITION_OPS, NUMERIC_CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
import { cleanPromptText, MAX_VOICE_CHARS } from "@/lib/npc-dialogue/normalize";
export const NpcDialogues: CollectionConfig = {
@ -79,7 +79,7 @@ export const NpcDialogues: CollectionConfig = {
type: "number",
admin: {
condition: (_data, blockData) =>
["gte", "lte", "gt", "lt", "eq"].includes(String(blockData?.op)),
NUMERIC_CONDITION_OPS.includes(String(blockData?.op) as never),
description: "Right-hand side for the numeric comparisons.",
},
},

View file

@ -27,7 +27,12 @@ import type {
NpcDialogueEffect,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, EFFECT_TYPES, outgoingHops } from "@/lib/npc-dialogue/dialogue";
import {
conditionSummary,
EFFECT_TYPES,
NUMERIC_CONDITION_OPS,
outgoingHops,
} from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { MarkupEditor } from "./MarkupEditor";
import { LineAssist } from "./LineAssist";
@ -64,6 +69,8 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
is_true: "is true",
is_false: "is false",
is_defined: "is defined",
is_undefined: "is not defined",
gte: "is at least",
lte: "is at most",
gt: "is greater than",
@ -78,8 +85,9 @@ const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
nor: "No condition matches (NOR)",
};
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** Ops that compare against a number: the shared list, so the canvas summary,
* the entry-gate field and this dialog never disagree. */
const NUMERIC_OPS = NUMERIC_CONDITION_OPS;
/** A blank leaf used when switching into single mode or adding a group row. */
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };

View file

@ -78,6 +78,23 @@ Availability is double-gated: `game-npcs.canMessage` on the contact, and the
`entryGate` / `priority` on the dialogue document selecting which of an NPC's
conversations is offered.
## Flag conditions
Leaves test a `player-flags` value for the reading player, falling back to the
global entry (`user: null`). `is_true` / `is_false` test truthiness, so a flag
explicitly set to false reads the same as a missing one; use `is_defined` /
`is_undefined` when the branch turns on whether a value was ever recorded. A
flag whose `activatesAt` is still in the future counts as defined (recorded, not
yet in effect) and reads false. An expired personal entry falls through to the
global entry rather than reading as absent.
`NUMERIC_CONDITION_OPS` in `dialogue.ts` is the single list of ops that take
`amount`; the editor, the `entryGate` field visibility and `conditionSummary`
all read it. Adding an op to `CONDITION_OPS` also changes the
`enum_npc_dialogues_entry_gate_op` Postgres enum, so it needs a migration
(`ALTER TYPE ... ADD VALUE`), not just a code change. `generationSchema.ts` keeps
its own copy of the op list for the drafting schema; update both.
## Text markup
Lines support `**bold**`, `*italic*`, `{red}color{/}`, `` `code` ``, `![alt](url)`,

View file

@ -59,7 +59,9 @@ export interface ChoiceGate {
* Branch condition evaluated server-side against live web-app state when the
* conversation arrives at a `condition` node. Boolean flags compare against
* true/false; numeric flags compare against `amount` (a missing flag counts
* as false / zero).
* as false / zero). The defined checks test whether the reading player has a
* recorded value at all, which no truthiness test can express: a missing flag
* and a flag explicitly set to false both read as false.
*/
export interface DialogueFlagCondition {
/** Currently only generic player flags; more kinds can join later. */
@ -67,8 +69,20 @@ export interface DialogueFlagCondition {
/** `player-flags` key checked for the reading user. */
key: string;
/** Comparison applied to the flag's effective value. */
op: "is_true" | "is_false" | "gte" | "lte" | "gt" | "lt" | "eq";
/** Right-hand side for the numeric comparisons. */
op:
| "is_true"
| "is_false"
| "is_defined"
| "is_undefined"
| "gte"
| "lte"
| "gt"
| "lt"
| "eq";
/**
* Right-hand side for the numeric comparisons. Ignored by the state checks
* (`is_true` / `is_false` / `is_defined` / `is_undefined`).
*/
amount?: number;
}
@ -90,6 +104,22 @@ export type DialogueCondition = DialogueFlagCondition | DialogueConditionGroup;
export const CONDITION_OPS: DialogueFlagCondition["op"][] = [
"is_true",
"is_false",
"is_defined",
"is_undefined",
"gte",
"lte",
"gt",
"lt",
"eq",
];
/**
* Ops that compare the flag against `amount`. Everything else tests the flag's
* state (truthiness or existence), so the amount is meaningless for them and
* the UI hides it. Shared so the editor, the entry-gate field and the canvas
* summary never disagree about which ops take a number.
*/
export const NUMERIC_CONDITION_OPS: DialogueFlagCondition["op"][] = [
"gte",
"lte",
"gt",
@ -444,7 +474,7 @@ export function connectHop(
export function conditionSummary(condition: DialogueCondition): string {
const leaf = (c: DialogueFlagCondition): string =>
`"${c.key || "?"}" ${c.op.replace(/_/g, " ")}${
c.amount !== undefined && !["is_true", "is_false"].includes(c.op) ? ` ${c.amount}` : ""
c.amount !== undefined && NUMERIC_CONDITION_OPS.includes(c.op) ? ` ${c.amount}` : ""
}`;
if (condition.kind === "group") {
const joiner = condition.op === "and" ? " and " : condition.op === "or" ? " or " : " and ";

View file

@ -104,8 +104,14 @@ export async function readFlag(
});
const playerDoc = playerRes.docs[0];
if (playerDoc) {
if (!activeNow(playerDoc)) return inactiveValues(playerDoc);
return flagValues(playerDoc);
// Pending activation: the value is recorded but not in effect yet, so it
// reads inactive now while still counting as defined and carrying its
// countdown target.
if (pendingActivation(playerDoc)) return inactiveValues(playerDoc);
// Active: this is the value.
if (activeNow(playerDoc)) return flagValues(playerDoc);
// Expired: the personal entry no longer applies, so fall through to the
// global fallback below (matching the contract in this function's doc).
}
// Global fallback (user is null).
@ -174,6 +180,13 @@ export async function evaluateCondition(
return flag.bool;
case "is_false":
return !flag.bool;
// Existence, not truthiness: a flag explicitly set to false is defined,
// and a missing one is not. A not-yet-active flag counts as defined (its
// value is recorded, it just has not taken effect), matching `exists`.
case "is_defined":
return flag.exists;
case "is_undefined":
return !flag.exists;
case "gte":
return flag.num >= amount;
case "lte":

View file

@ -37,7 +37,17 @@ export const DRAFT_NODE_TYPES = ["dialogue", "choice", "event", "end", "conditio
export const DRAFT_EFFECT_TYPES = ["none", "flag", "notify"] as const;
const FLAG_OPS = ["set_true", "set_false", "set_number", "set_text", "add"] as const;
const CONDITION_OPS = ["is_true", "is_false", "gte", "lte", "gt", "lt", "eq"] as const;
const CONDITION_OPS = [
"is_true",
"is_false",
"is_defined",
"is_undefined",
"gte",
"lte",
"gt",
"lt",
"eq",
] as const;
export interface RawDraftChoice {
label: string;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_npc_dialogues_entry_gate_op" ADD VALUE 'is_defined' BEFORE 'gte';
ALTER TYPE "public"."enum_npc_dialogues_entry_gate_op" ADD VALUE 'is_undefined' BEFORE 'gte';`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DATA TYPE text;
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DEFAULT 'is_true'::text;
DROP TYPE "public"."enum_npc_dialogues_entry_gate_op";
CREATE TYPE "public"."enum_npc_dialogues_entry_gate_op" AS ENUM('is_true', 'is_false', 'gte', 'lte', 'gt', 'lt', 'eq');
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DEFAULT 'is_true'::"public"."enum_npc_dialogues_entry_gate_op";
ALTER TABLE "npc_dialogues" ALTER COLUMN "entry_gate_op" SET DATA TYPE "public"."enum_npc_dialogues_entry_gate_op" USING "entry_gate_op"::"public"."enum_npc_dialogues_entry_gate_op";`)
}

View file

@ -166,6 +166,7 @@ import * as migration_20261121_015435_add_mission_attendance_unlocks from './202
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections';
import * as migration_20261124_223219_add_defined_condition_ops from './20261124_223219_add_defined_condition_ops';
export const migrations = [
{
@ -1006,6 +1007,11 @@ export const migrations = [
{
up: migration_20261124_175950_add_ai_connections.up,
down: migration_20261124_175950_add_ai_connections.down,
name: '20261124_175950_add_ai_connections'
name: '20261124_175950_add_ai_connections',
},
{
up: migration_20261124_223219_add_defined_condition_ops.up,
down: migration_20261124_223219_add_defined_condition_ops.down,
name: '20261124_223219_add_defined_condition_ops'
},
];

View file

@ -3039,7 +3039,7 @@ export interface NpcDialogue {
/**
* Comparison applied to the flag's effective value.
*/
op?: ('is_true' | 'is_false' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
op?: ('is_true' | 'is_false' | 'is_defined' | 'is_undefined' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
/**
* Right-hand side for the numeric comparisons.
*/

View file

@ -157,4 +157,76 @@ describe("condition groups (and / or / nor over leaf conditions)", () => {
expect(validation.valid).toBe(false);
expect(validation.errors.join(" ")).toContain("needs a flag key");
});
it(
"tells an absent flag apart from one set to false, and counts a pending flag as defined",
async () => {
const user = await createUser(`${RUN}_defined`);
const key = `${RUN}_reported`;
await applyFlagEffect(payload, user, key, "set_false", 0);
await applyFlagEffect(payload, user, `${RUN}_later`, "set_true", 0, undefined, 60);
const check = (k: string, op: DialogueFlagCondition["op"]) =>
evaluateCondition(payload, user, { kind: "flag", key: k, op });
// A recorded false is defined; a truthiness test cannot express this.
expect(await check(key, "is_defined")).toBe(true);
expect(await check(key, "is_undefined")).toBe(false);
expect(await check(key, "is_true")).toBe(false);
expect(await check(key, "is_false")).toBe(true);
// Nothing recorded at all.
expect(await check(`${RUN}_never`, "is_defined")).toBe(false);
expect(await check(`${RUN}_never`, "is_undefined")).toBe(true);
// Scheduled for later: recorded, so defined, but not yet in effect.
expect(await check(`${RUN}_later`, "is_defined")).toBe(true);
expect(await check(`${RUN}_later`, "is_true")).toBe(false);
},
TIMEOUT,
);
it(
"falls back to the global entry once a personal flag expires",
async () => {
const user = await createUser(`${RUN}_expiry`);
const key = `${RUN}_shared`;
// Personal entry already expired; global entry still active.
await payload.create({
collection: "player-flags",
data: {
user,
key,
flagType: "boolean",
boolValue: false,
expiresAt: new Date(Date.now() - 60_000).toISOString(),
},
overrideAccess: true,
});
await applyFlagEffect(payload, null, key, "set_true", 0);
const leaf = (op: DialogueFlagCondition["op"]): DialogueFlagCondition => ({
kind: "flag",
key,
op,
});
expect(await evaluateCondition(payload, user, leaf("is_true"))).toBe(true);
expect(await evaluateCondition(payload, user, leaf("is_defined"))).toBe(true);
},
TIMEOUT,
);
it("summarises defined checks without a stray amount", () => {
expect(
conditionSummary({
kind: "flag",
key: "met_informant",
op: "is_defined",
amount: 3,
}),
).toBe('"met_informant" is defined');
expect(
conditionSummary({ kind: "flag", key: "met_informant", op: "is_undefined" }),
).toBe('"met_informant" is undefined');
});
});