1
0
Fork 0
polaris-task-force/tests/int/npc-dialogue-condition-groups.int.spec.ts
Z8MB1E 938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler
only reuses worker processes between isolate:false tasks, so per-file fork
spawning made clone+boot costs unavoidable at stage 2):

- config: workers branch runs pool=forks with isolate:false, cap 8 via
  VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs),
  failure-marker reporter, and idempotent setupFiles chain
- vitest-worker-setup: one template clone PER FORK PROCESS named by pid
  (VITEST_WORKER_ID churns per task, which silently re-cloned per file);
  DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3)
- vitest.setup: once-per-process serial test URI markers; afterEach
  useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock
  module factories mid-file); logging absorber for fire-and-forget event
  writes that reject after their spec's cleanup deleted fixture users
- helpers/get-test-payload.ts: memoized Payload boot shared across files
  in a fork; codemod converted all 91 self-booting specs mechanically
- pinned opt-outs (own boot + comments): game-structures-labor-route,
  mission-reminder, notification-inbox-scope (jwtSign writes leak into
  the shared instance's auth state across files)
- promotion-nominations: create the superuser before its rank ladder so
  the Users-hook Recruit rank gets leading orderable tokens (its
  top-of-ladder guard needs Col to remain ladder-max on fresh clones);
  operation-economy: itemType-scope the market-state assertion (asset
  and resource ids collide as bare integers under per-fork databases)

Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s
vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4
note: globalTeardown config no longer exists; teardown returns from
globalSetup.
2026-10-21 12:54:30 -04:00

160 lines
5.2 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DialogueCondition, DialogueFlagCondition } from "@/lib/npc-dialogue/dialogue";
import { applyFlagEffect, evaluateCondition } from "@/lib/npc-dialogue/flags";
import { conditionSummary, hasEmptyConditionKey, validateGraph } from "@/lib/npc-dialogue/dialogue";
let payload: Payload;
const RUN = `grp_${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const userIds: number[] = [];
async function createUser(username: string): Promise<number> {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `GRP ${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.id;
}
describe("condition groups (and / or / nor over leaf conditions)", () => {
beforeAll(async () => {
payload = await getTestPayload();
}, 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(
"combines leaves with and / or / nor against live flags",
async () => {
const user = await createUser(`${RUN}_combo`);
await applyFlagEffect(payload, user, `${RUN}_a`, "set_true", 0);
await applyFlagEffect(payload, user, `${RUN}_rep`, "set_number", 7);
const leafA: DialogueFlagCondition = { kind: "flag", key: `${RUN}_a`, op: "is_true" };
const leafMissing: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_nope`,
op: "is_true",
};
const leafRep: DialogueFlagCondition = { kind: "flag", key: `${RUN}_rep`, op: "gte", amount: 5 };
const leafRepFail: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_rep`,
op: "gte",
amount: 99,
};
const evalGroup = (op: "and" | "or" | "nor", children: DialogueFlagCondition[]) =>
evaluateCondition(payload, user, { kind: "group", op, children });
expect(await evalGroup("and", [leafA, leafRep])).toBe(true);
expect(await evalGroup("and", [leafA, leafMissing])).toBe(false);
expect(await evalGroup("or", [leafMissing, leafRep])).toBe(true);
expect(await evalGroup("or", [leafMissing, leafRepFail])).toBe(false);
expect(await evalGroup("nor", [leafMissing, leafRepFail])).toBe(true);
expect(await evalGroup("nor", [leafA, leafRepFail])).toBe(false);
},
TIMEOUT,
);
it(
"treats empty groups as vacuous (and/nor pass, or fails) and leaves still work",
async () => {
const user = await createUser(`${RUN}_empty`);
expect(await evaluateCondition(payload, user, { kind: "group", op: "and", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "nor", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "or", children: [] })).toBe(
false,
);
// A plain leaf keeps its old semantics.
expect(
await evaluateCondition(payload, user, { kind: "flag", key: `${RUN}_x`, op: "is_false" }),
).toBe(true);
},
TIMEOUT,
);
it("summarises and validates groups for the editor", () => {
const group: DialogueCondition = {
kind: "group",
op: "or",
children: [
{ kind: "flag", key: "met_informant", op: "is_true" },
{ kind: "flag", key: "rep", op: "gte", amount: 5 },
],
};
expect(conditionSummary(group)).toBe('"met_informant" is true or "rep" gte 5');
expect(hasEmptyConditionKey(group)).toBe(false);
expect(
hasEmptyConditionKey({
kind: "group",
op: "and",
children: [{ kind: "flag", key: " ", op: "is_true" }],
}),
).toBe(true);
expect(hasEmptyConditionKey({ kind: "group", op: "and", children: [] })).toBe(true);
const nodes = [
{
id: "start",
type: "dialogue" as const,
position: { x: 0, y: 0 },
data: { isStart: true, body: "hi", next: { target: "c1" } },
},
{
id: "c1",
type: "choice" as const,
position: { x: 0, y: 0 },
data: {
choices: [
{
label: "Ask",
target: "",
condition: {
kind: "group" as const,
op: "and" as const,
children: [{ kind: "flag" as const, key: " ", op: "is_true" as const }],
},
},
],
},
},
];
const validation = validateGraph(nodes);
expect(validation.valid).toBe(false);
expect(validation.errors.join(" ")).toContain("needs a flag key");
});
});